在线程之间传递数据是很常见的事情。python中的Queue模块可以为我们自动控制线程锁,保证数据同步。

Queue类实现了一个基本的先进先出(FIFO)容器,使用put将元素添加到序列尾端,用get从序列中移除元素。

单线程的队列比较简单,就不提了。

这里写了一个例程,主要是将队列与多线程结合起来使用。

import queue
import threading
import time


#创建工作队列并限定队列的最大元素是10个
work_queue = queue.Queue(maxsize=10)

#创建结果队列并限制队列的最大元素是10个
result_queue = queue.Queue(maxsize=10)


class WorkThread(threading.Thread):
    def __init__(self, thread_id):
        super(WorkThread, self).__init__()
        self.thread_id = thread_id

    def run(self):
        while not work_queue.empty():
            work = work_queue.get()
            time.sleep(3)
            out = 'Thread %d\t received %s' %( self.thread_id, work)
            result_queue.put(out)


def main():
    for i in range(10):
        work_queue.put('message id %d' %i)
    #开启两个工作线程
    for i in range(2):
        thread = WorkThread(i)
        thread.start()
    for i in range(10):
        print(result_queue.get())

if __name__ == '__main__':
    main()

你也可能喜欢

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注