python thread+queue

# -*- coding: utf-8 -*-#
import threading
import time
from queue import Queue


def do(name):
    print(name)
    time.sleep(0.1)


def task(name):
    if not message_queue.full():
        message_queue.put(name)
    else:
        time.sleep(0.1)


def receive_message():
    while True:
        message = message_queue.get()
        do(message)
        message_queue.task_done()


def run():
    for i in range(10):
        task(i)


if __name__ == '__main__':
    s_time = time.time()
    message_queue = Queue(20)
    for _ in range(5):
        file_worker = threading.Thread(target=receive_message, daemon=True)
        file_worker.start()
    run()
    message_queue.join()
    print(f"耗时:{time.time() - s_time}")


posted @ 2023-01-09 16:25  不能说的秘密  阅读(37)  评论(0编辑  收藏  举报