2017-02-02 6 views
0

Ich weiß nicht, warum der Code unten funktioniert. Der Teil steckte ich bin an istMultithreaded Inkrement Verständnis Bestellung

for t in worker_threads: 
    t.join() 

Für mich ist das alles für jeden worker Thread zu .put(1) in counter_queue nicht warten.

Ich bin nicht ganz sicher, der Zweck dieser Zeilen wie del t zerstört sie sofort. Ich könnte die Bedeutung dieser wiederholten Linien fehlen:

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

Gibt es etwas, das ich ein fehlt in Bezug auf die .daemon Flagge? oder gibt es noch etwas anderes?

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() 

Ausgang:

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 

Antwort

0

So stellt sich heraus, dass ich ein Missverständnis der Funktionalität del hatte. del dereferenziert tatsächlich das Objekt/den Thread. Es existiert immer noch im Hintergrund und läuft immer noch und lauscht auf Eingaben!