使用Queue模块实现线程间通讯
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Queue模块实现线程间通讯相关的知识,希望对你有一定的参考价值。
import threading from random import randint from time import sleep from Queue import Queue class MyThread(threading.Thread): def __init__(self, queue, func, loop): super(MyThread, self).__init__() self.queue = queue self.func = func self.loop = loop def run(self): self.func(self.queue, self.loop) def writer(q, loops): for i in range(loops): s = randint(100, 200) strs = "xxx-%s" % (s) q.put(strs, block=1) print("Write data: {}, Queue Size now: {}".format(strs, q.qsize())) sleep(randint(1, 8)) def reader(q, loops): for i in range(loops): val = q.get(block=1) print("Read value: {}, Queue Size now: {}".format(val, q.qsize())) sleep(randint(2, 10)) def main(): funcs = [writer, reader] nfuncs = range(len(funcs)) nloops = randint(1,8) q = Queue(32) threads = [] for i in nfuncs: t = MyThread(q, funcs[i], nloops) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print(" all DONE !!!") if __name__ == '__main__': main()以上是关于使用Queue模块实现线程间通讯的主要内容,如果未能解决你的问题,请参考以下文章
进程间数据传递:Queue,Pipe 进程间数据共享:Manager