线程中使用的Python队列 - 订单保留?

时间:2017-06-22 15:39:12

标签: python multithreading

这与执行顺序无关 - 它与输出存储在python中的队列中的顺序有关。

基本问题 -

我有10个线程将函数应用于参数队列,结果在另一个队列中。是否保证参数的顺序和两个队列中的结果是相同的?我的代码似乎建议如此.`

import Queue
import threading
import time
import random

print_lock = threading.Lock() 
r = random.Random()
r.seed=5

def calc(num_q, q):  

    while True:

        number = num_q.get()

        with print_lock:
            print(threading.current_thread().name,number)  
        #print(number)
        q.put(number)
        time.sleep(r.randint(0,5))
        num_q.task_done()
        q.task_done()

#threads=[]

numbers =[z for z in range(20)]

num_q = Queue.Queue(maxsize=0)
q = Queue.Queue(maxsize=0)

num_threads = 10

for x in range(num_threads):
    t = threading.Thread(target=calc, args=(num_q,q))
    t.daemon= True
    #threads.append(t)
    t.start()

start = time.time()  
for n in numbers:
    num_q.put(n)

num_q.join()
print('Entire job took:',time.time() - start)
while q.empty() is False:
    print(q.get())`

0 个答案:

没有答案