2017-02-02 53 views
0

我不知道爲什麼下面的代碼工作。我停留在部分多線程增量了解訂購

for t in worker_threads: 
    t.join() 

對我來說,這一切都爲等待每個worker線程.put(1)counter_queue

我不太確定這些行的目的是否爲del t立即銷燬它們。我可能會丟失這些重複行的意義:

t = threading.Thread(target=print_manager) 
t.daemon = True 
t.start() 
del t 

有什麼我缺少關於.daemon標誌?還是還有別的東西?

import threading, queue 

########################################################################################### 

counter = 0 

counter_queue = queue.Queue() 

def counter_manager(): 
    'I have EXCLUSIVE rights to update the counter variable' 
    global counter 

    while True: 
     increment = counter_queue.get() 
     counter += increment 
     print_queue.put([ 
      'The count is %d' % counter, 
      '---------------']) 
     counter_queue.task_done() 

t = threading.Thread(target=counter_manager) 
t.daemon = True 
t.start() 
del t 

########################################################################################### 

print_queue = queue.Queue() 

def print_manager(): 
    'I have EXCLUSIVE rights to call the "print" keyword' 
    while True: 
     job = print_queue.get() 
     for line in job: 
      print(line) 
     print_queue.task_done() 

t = threading.Thread(target=print_manager) 
t.daemon = True 
t.start() 
del t 

########################################################################################### 

def worker(): 
    'My job is to increment the counter and print the current count' 
    counter_queue.put(1) 

print_queue.put(['Starting up']) 
worker_threads = [] 
for i in range(10): 
    t = threading.Thread(target=worker) 
    worker_threads.append(t) 
    t.start() 
for t in worker_threads: 
    t.join() 

counter_queue.join() 
print_queue.put(['Finishing up']) 
print_queue.join() 

輸出:

Starting up 
The count is 1 
--------------- 
The count is 2 
--------------- 
The count is 3 
--------------- 
The count is 4 
--------------- 
The count is 5 
--------------- 
The count is 6 
--------------- 
The count is 7 
--------------- 
The count is 8 
--------------- 
The count is 9 
--------------- 
The count is 10 
--------------- 
Finishing up 

回答

0

因此,原來我有的del功能的誤解。 del實際上取消了對象/線程的引用。它仍然存在於後臺並仍在運行並正在監聽輸入!