PythonStudy——线程中的几种消息队列

Queue

from queue import Queue,LifoQueue,PriorityQueue

# 队列模块 queue
# 类 Queue
# 类 LifoQueue
# 类 PriorityQueue

# 与进程中的JoinableQueue 使用方式完全一样 但是没有IPC

q = Queue()

# 放入元素  put 方法
q.put("123")
q.put("456")
q.put("789")

# 取出元素  get方法
# 方法一 (基础版取值)
print(q.get())
print(q.get())

# 方法二 (高级版取值)
# 设置阻塞选项block 默认为True  )
# 设置超时选项timeout 默认为None
# 如果在阻塞情况下超时取不到值,则抛出异常
# get(self, block=True, timeout=None)
print(q.get(block=True,timeout=1))

# 告知队列任务完成
q.task_done()
# 优先完成当前队列任务,完成不了阻塞
# q.join()
from queue import Queue,LifoQueue,PriorityQueue

# 队列模块 queue
# 类 Queue
# 类 LifoQueue
# 类 PriorityQueue

# 与进程中的JoinableQueue 使用方式完全一样 但是没有IPC

q = Queue()

# 放入元素  put 方法
q.put("123")
q.put("456")
q.put("789")

# 取出元素  get方法
# 方法一 (基础版取值)
print(q.get())
print(q.get())

# 方法二 (高级版取值)
# 设置阻塞选项block 默认为True  )
# 设置超时选项timeout 默认为None
# 如果在阻塞情况下超时取不到值,则抛出异常
# get(self, block=True, timeout=None)
print(q.get(block=True,timeout=1))

# 告知队列任务完成
q.task_done()
# 优先完成当前队列任务,完成不了阻塞
# q.join()

LifoQueue

from queue import LifoQueue

# last in first out
# 后进先出队列
# 先进后出 模拟堆栈
# 除了顺序以外 其他都一样
lifoqueue = LifoQueue()

lifoqueue.put("123")
lifoqueue.put("456")
lifoqueue.put("789")

print(lifoqueue.get())
print(lifoqueue.get())
print(lifoqueue.get())

PriorityQueue

from queue import PriorityQueue


# 具备优先级的队列
# 可以存储一个可以比较大小的对象
# 比较结果越小的优先级越高
# 自定义的对象,除非定义了__eq__方法,否则是无法进行比较的(不能使用比较运算符) 所以不能存储

# pq = PriorityQueue()
# pq.put("222")
# pq.put("111")
# pq.put("333")
# pq.put(34234)
# TypeError: '<' not supported between instances of 'int' and 'str'
# 需要保证存入优先队列内部的值是同一个类型

# print(pq.get())
# print(pq.get())
# print(pq.get())


# 类的比较运算模拟
class Aa(object):
    # 初始化
    def __init__(self, num):
        self.num = num

    # 小于运算 litter than
    def __lt__(self, other):
        return self.num < other.num, "小于"

    # 小于等于 litter equal
    def __le__(self, other):
        return self.num <= other.num,"小于等于"

    # 大于运算 greater than
    def __gt__(self, other):
        return self.num > other.num, "大于"

    # 大于等于 greater equal
    def __ge__(self, other):
        return self.num >= other.num,"大于等于"

    # 等于运算 equal
    def __eq__(self, other):
        return self.num == other.num,"等于"

    # 不等于 not equal
    def __ne__(self, other):
        return self.num != other.num,"不等于"

print(Aa(100) >= Aa(200))
print(Aa(100) <= Aa(200))
print(Aa(100) > Aa(200))
print(Aa(100) < Aa(200))
print(Aa(100) != Aa(200))
print(Aa(100) == Aa(200))
# (False, '大于等于')
# (True, '小于等于')
# (False, '大于')
# (True, '小于')
# (True, '不等于')
# (False, '等于')

 

posted @ 2019-06-08 15:07  挺锅锅  阅读(424)  评论(0编辑  收藏  举报