python 多线程 queue先进先出队列(并行编程 8)

from queue import Queue
import random
import threading
import time

Producer thread

class Producer(threading.Thread):
def init(self, t_name, queue):
threading.Thread.init(self, name=t_name)
self.data = queue

def run(self):
    for i in range(5):
        print("%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), i))
        self.data.put(i)
        time.sleep(random.randrange(10) / 5)
    print("%s: %s finished!" % (time.ctime(), self.getName()))

Consumer thread

class Consumer(threading.Thread):
def init(self, t_name, queue):
threading.Thread.init(self, name=t_name)
self.data = queue

def run(self):
    for i in range(5):
        val = self.data.get()
        print("%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val))
        time.sleep(random.randrange(10))
    print("%s: %s finished!" % (time.ctime(), self.getName()))

Main thread

def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer = Consumer('Con.', queue)
producer.start()
consumer.start()
producer.join()
consumer.join()
print('All threads terminate!')

if name == 'main':
main()

import queue

q = queue.Queue(3) # 调用构造函数,初始化一个大小为3的队列
print(q.empty()) # 判断队列是否为空,也就是队列中是否有数据

入队,在队列尾增加数据, block参数,可以是True和False 意思是如果队列已经满了则阻塞在这里,

timeout 参数 是指超时时间,如果被阻塞了那最多阻塞的时间,如果时间超过了则报错。

q.put(13, block=True, timeout=5)
print(q.full()) # 判断队列是否满了,这里我们队列初始化的大小为3
print(q.qsize()) # 获取队列当前数据的个数

block参数的功能是 如果这个队列为空则阻塞,

timeout和上面一样,如果阻塞超过了这个时间就报错,如果想一只等待这就传递None

print(q.get(block=True, timeout=None))

queue模块还提供了两个二次封装了的函数,

q.put_nowait(23) # 相当于q.put(23, block=False)
q.get_nowait() # 相当于q.get(block=False)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容