并发编程之队列

队列:

from queue import Queue,LifoQueue,PriorityQueue

以上三种队列有什么不同?

1. Queue 与 joinableQueue类似

2. LifoQueue(栈,特点:后进先出)

from queue import Queue,LifoQueue,PriorityQueue
a = LifoQueue()     # 后进先出,栈。跟对列相比,仅是取得顺序不同
a.put(1)
a.put(2)
a.put(3)
print(a.get())
print(a.get())
print(a.get())
3
2
1

3. PriorityQueue(具备优先级的队列)

第1阶段:数字小优先级越高(进队列会排序:从小到大)
from queue import Queue,LifoQueue,PriorityQueue
q = PriorityQueue() # 具备优先级的队列,取数据时,值越小,优先级越高
q.put(1)
q.put(3)
q.put(2)

print(q.get())
print(q.get())
print(q.get())


# 比较两个元组中的数据
b  = (1,2,3,4,5)
c = (0.9,2,3,4)
d = (5,1,4,5)

q.put(b)
q.put(c)
q.put(d)

print(q.get())
print(q.get())
print(q.get())
1
2
3
(0.9, 2, 3, 4)
(1, 2, 3, 4, 5)
(5, 1, 4, 5)
第2阶段:两个类如何比较(运算符重载,重写父类的“比较大小”的方法)

需求:比较两个人的年龄,从小到大排序;如果年龄相等,则按照姓名排序。

from queue import PriorityQueue

# 定义类
class person():
    def __init__(self,name,age):
        self.name = name
        self.age = age
	
    # 重写运算符。即运算符重载
    def __lt__(self, other):
        if self.age == other.age:
            return self.name < other.name
        return self.age < other.age

# 创建队列
q = PriorityQueue()

p1 = person('ack',18)
p2 = person('boo',18)
p3 = person("hehe",17)

q.put(p1)	# ack  18
q.put(p2)	# boo   18
q.put(p3)	# hehe  17

print(q.get().name)
print(q.get().name)
print(q.get().name)
hehe
ack
boo

运算符重载即 重写运算符方法。

原文地址:https://www.cnblogs.com/plf-Jack/p/11153094.html