多线程队列打印编号偶尔会丢失换行符/格式(Python)

时间:2019-07-17 21:11:58

标签: python-3.x multithreading queue

我正在使用队列和工作程序结构测试多线程,每个工作程序包装并调用我的print_name函数。在执行过程中,某些打印语句显示为束,而不是在自己的行上打印每个语句。我尝试过改变线程数和正在打印的内容的范围,但是格式化错误仍然存​​在。我不太确定为什么会这样,而且对于使用队列/工作器的多线程技术我还很陌生,因此请多多指教,谢谢!

import queue
import threading

def print_name(name):
    print(name)

def worker(q):
    while True:
        item = q.get()
        print_name(item)
        q.task_done()

q = queue.Queue()
for i in range(50):
    t = threading.Thread(target = worker, args = (q,))
    t.start()
fullset = [x for x in range(1000)]
for name in fullset:
    q.put(name)
Sample Output:

914
915


916
917




918
919920921
922

923924
925
926
927
928
929
930

Desired Output --  not necessarily in order, just on each separate line
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930

0 个答案:

没有答案
相关问题