2011-04-14 3 views
2

모든 이봐, 내가 (마크 루츠 파이썬 프로그래밍 에서) 다음 코드의 일부를 이해 드릴 수 없습니다 : 나는 Python3을 사용하고파이썬 스레딩

import _thread as thread 

stdoutmutex = thread.allocate_lock() 
exitmutexes = [thread.allocate_lock() for i in range(10)] 

def counter(myId, count): 
    for i in range(count): 
     stdoutmutex.acquire() 
     print('[%s] => %s' % (myId, i)) 
     stdoutmutex.release() 
    exitmutexes[myId].acquire() 

# signal main thread 
for i in range(10): 
    thread.start_new_thread(counter, (i, 100)) 

for mutex in exitmutexes: 
    while not mutex.locked(): pass 
print('Main thread exiting.') 

. 글쎄, 나는 stdoutmutex 일을 이해할 수있어 그것은 어떻게 작동하지만, exitmutexes의 개별 잠금 획득,하지만 출시 된 때문에, 위의 코드는 exitmutexes 목록을 처리하는 방법을 이해 할 수없는거야 . 10 개의 스레드가 모두 시작된 후 아래의 3 줄은 어떻게 작동합니까? 저자는 time.sleep를 사용하지 않고가는 방법() 모든 출구 뮤텍스가 다음 종료 잠겨 때까지 그것은 기본적으로 대기

for mutex in exitmutexes: 
     while not mutex.locked(): pass 
    print('Main thread exiting.') 
+0

잠금을 획득하면 스레드가 활성 상태를 유지합니까? – kaiseroskilo

답변

0

으로 이것을 설명했다. 출구 뮤텍스 이상하고 뮤텍스를 기다리는 루프에 들어갑니다 각 뮤텍스에 대한

for mutex in exitmutexes: 
    while not mutex.locked(): pass 

이 코드의 반복을 잠글 수 있습니다.

그러나 "매우 적극적인 대기"기능을 사용하므로 CPU 사용량이 매우 높습니다 (아무 것도하지 않는 무한 루프처럼). 이는 매우 나쁜 일입니다.