Python 变量在线程中更新,但更新的值不会反映在循环中
我正在学习Mark Lutz编写Python时的多线程,遇到了以下示例:Python 变量在线程中更新,但更新的值不会反映在循环中,python,multithreading,Python,Multithreading,我正在学习Mark Lutz编写Python时的多线程,遇到了以下示例: import _thread as thread stdoutmutex = thread.allocate_lock() exitmutexes = [thread.allocate_lock() for i in range(5)] def counter(myId, count): for i in range(count): stdoutmutex.acquire() p
import _thread as thread
stdoutmutex = thread.allocate_lock()
exitmutexes = [thread.allocate_lock() for i in range(5)]
def counter(myId, count):
for i in range(count):
stdoutmutex.acquire()
print('[%s] => %s' % (myId, i))
stdoutmutex.release()
exitmutexes[myId].acquire()
for i in range(5):
thread.start_new_thread(counter, (i, 20))
for mutex in exitmutexes:
while not mutex.locked(): pass
print('Main thread exiting.')
上面的代码运行良好。它为每个子线程使用互斥锁,并将它们固定到全局exitmutex
列表中。在退出时,每个线程通过打开其锁向主线程发送信号
我想我可以使用通用布尔标志,而不是allocate\u lock()
。因此,我将上述代码修改为:
import _thread as thread
stdoutmutex = thread.allocate_lock()
exitmutexes = [False for i in range(5)]
def counter(myId, count):
for i in range(count):
stdoutmutex.acquire()
print('[%s] => %s' % (myId, i))
stdoutmutex.release()
exitmutexes[myId] = True
for i in range(5):
thread.start_new_thread(counter, (i, 20))
for mutex in exitmutexes:
while not mutex: print(exitmutexes)
print('Main thread exiting.')
我的版本不起作用。它只是不断循环。为什么简单的布尔标志在这里不起作用?谢谢 互斥体是一个循环变量。它在第i次迭代时接收
exitmutex[i]
中的值的快照,以便在更新exitmutex[i]
时,在mutex
中看不到更改。所以
while not mutex
将不断测试该条目的旧值,即使该条目已更新。您应该迭代索引:
for i in range(len(exitmutexes)):
while not exitmutexes[i]: print(exitmutexes[i])
或者,使用枚举
:
for i, mutex in enumerate(exitmutexes):
while not exitmutexes[i]: print(mutex)
而不是互斥
不会重新读取列表项。