1. 程式人生 > >使用Queue模塊實現線程間通訊

使用Queue模塊實現線程間通訊

python線程間通訊

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模塊實現線程間通訊