调用get()后python线程安全队列是如何工作的

gmxoilav  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(280)

在文档中的示例中:

import threading, queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on {item}')
        print(f'Finished {item}')
        q.task_done()

# turn-on the worker thread

threading.Thread(target=worker, daemon=True).start()

# send thirty task requests to the worker

for item in range(30):
    q.put(item)
print('All task requests sent\n', end='')

# block until all tasks are done

q.join()
print('All work completed')

在工作线程从队列中获得后(我假设它受到一些锁的保护),检查队列并修改队列是原子的,它会打印。如何在所有工作线程中打印原子,而我们不会看到混合打印?

ezykj2lf

ezykj2lf1#

线程打印到stdout,这是一个共享的全局对象。一种可能的解决方案是使用threading.lock或threading.semaphore来保护标准输出。例如:

import threading, queue

print_semaphore = threading.Semaphore()

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        with print_semaphore:
            print(f'Working on {item}')
            print(f'Finished {item}')
        q.task_done()

# turn-on the worker thread

threading.Thread(target=worker, daemon=True).start()

# send thirty task requests to the worker

for item in range(99):
    q.put(item)
    with print_semaphore:
        print('All task requests sent\n', end='')

# block until all tasks are done

q.join()
with print_semaphore:
    print('All work completed')

另一种解决方案是引入另一个队列,让线程将消息放入该队列,而不是直接打印到标准输出。

相关问题