Python 多线程队列

Gre*_*yte 4 python queue multithreading python-3.x

import threading
from queue import Queue



print_lock = threading.Lock()
def job(worker):
    with print_lock:
        with open('messages.txt') as f:
            for line in f:
                print(line)

def reader():
    while True:
        worker = q.get()
        job(worker)
        q.task_done()

q = Queue()

for x in range(10):
    t = threading.Thread(target=reader)

    t.daemon = True
    t.start()


for worker in range(1):
    q.put(worker)

q.join()
Run Code Online (Sandbox Code Playgroud)

所以我想要的是每个线程读取不同的消息,

yix*_*yan 5

队列是线程安全的

所以,不需要线程锁