2017-02-02 7 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 фактически разыгрывает объект/нить. Он все еще существует в фоновом режиме и все еще работает и прослушивает ввод!