python自带队列queue使用生产者消费者多线程使用

生产者消费者代码示例:

import time
from queue import Queue
from threading import Thread


q = Queue(maxsize=3)


def consumer():
    print('消费者线程启动')
    while True:
        print('开始消费',q.get())
        time.sleep(2)
        q.task_done()

def size():
    while not q.empty():
        print('队列长度--->',q.qsize())
        time.sleep(1)

def producer():
    print('生产者线程启动')
    for i in range(10):
        q.put(i)

if __name__ == '__main__':


    t1 = Thread(target=producer)

    t2 = Thread(target=consumer)
    t3 = Thread(target=size)
    t1.start()
    t2.start()
    t3.start()

你可能感兴趣的:(随笔,python,开发语言,后端)