并发编程——线程queue

1 线程queue

1.1 先进先出 Queue

# 看下类Queue的注释

class Queue:
    '''Create a queue object with a given maximum size.
    If maxsize is <= 0, the queue size is infinite.
    '''
import queue
q = queue.Queue(3)  # 给定最大值,如果给定值 <= 0,queue是无穷的

q.put([1,2,3])
q.put(1)
q.put(2)
q.put(3)   # 超过给定值就会阻塞住,不报错

q.put()有两个参数,

def put(self, item, block=True,timeout=None)

如果block=False,不阻塞,超过给定值直接报错,等于put_nowait,

def put_nowait(self, item)
    return self.put(item, block=False)

如果block=True,timeout设置阻塞时间,超过时间报错。

# q.put(4,block=False) # 报错
# raise Full

# q.put_nowait(4)
# raise Full

# q.put(4,block=True,timeout=3)  # 如果block 为true,阻塞时间timeout,超时报错
# raise Full
print(q.get())
print(q.get())
print(q.get())
print(q.get())   # 取完再取也会阻塞

q.get()与put()一样,也有两个参数,也有get_nowait

def get(self, block=True, timeout=None)


def get_nowait(self)
    return self.get(block=False)
# print(q.get())
# print(q.get())
# print(q.get())
# print(q.get())  # 阻塞

# print(q.get(block= False))  # 报错
# raise Empty

# print(q.get_nowait())
# raise Empty

1.2 后进先出 LifoQueue

'''Variant of Queue that retrieves most recently added entries first.'''
q = queue.LifoQueue(3)  # last in first out 后进先出,堆栈
q.put(1)
q.put(2)
q.put(3)

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

# 3
# 2
# 1

1.3 优先级队列 PriorityQueue

数字越小,优先级越高,通常传入元祖形式,
(优先级编号,数据)

'''Variant of Queue that retrieves open entries in priority order (lowest first).

    Entries are typically tuples of the form:  (priority number, data).
    '''
q = queue.PriorityQueue(4)  # 优先级

q.put((4, '3'))
q.put((3, 'hello'))
q.put((5, '5'))
q.put((2, 'hello'))

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

结果也是元祖形式
(2, 'hello')
(3, 'hello')
(4, '3')
(5, '5')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值