2
嘿,我不能(通過馬克·魯茨編程的Python從)瞭解下面的代碼的某些部分:Python的線程
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.')
我使用Python3。嗯,我能理解stdoutmutex的事情,它是如何工作的,但我無法理解上面的代碼如何處理exitmutexes名單,因爲在exitmutexes個人鎖已被收購,但沒有公佈。一旦所有10個線程都開始運行,下面的3條線路如何工作?筆者曾形容,這是),而無需使用time.sleep去的方式(
for mutex in exitmutexes:
while not mutex.locked(): pass
print('Main thread exiting.')
獲取鎖是否使線程保持活動狀態? – kaiseroskilo 2012-02-27 10:50:00