[英]Variable is updated in a thread but updated value does not reflect inside a loop
I'm studying multithreading in Programming Python by Mark Lutz, and encountered the following example: 我正在研究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()
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.')
The above code works fine. 上面的代码工作正常。 It uses mutex for each child thread and tacks them onto a global
exitmutexes
list. 它为每个子线程使用互斥锁,并将它们添加到全局
exitmutexes
列表中。 On exit each thread signals the main thread by switching its lock on. 在退出时,每个线程都通过打开其锁来向主线程发出信号。
I thought I could use a general boolean flag, instead of allocate_lock()
. 我以为我可以使用一般的布尔标志,而不是
allocate_lock()
。 So I have modified the above code into this: 所以我将上面的代码修改为:
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.')
My version doesn't work. 我的版本不起作用。 It just looping on and on.
它只是不断循环。 Why is a simple boolean flag not working here?
为什么简单的布尔标志在这里不起作用? Thanks.
谢谢。
mutex
is a loop variable. mutex
是一个循环变量。 It receives a snapshot of the value in exitmutexes[i]
at the i th iteration, so that when exitmutexes[i]
is updated, the change is not seen in mutex
. 它接收到的值的快照
exitmutexes[i]
在第i 次迭代,从而当exitmutexes[i]
被更新时,变化不可见mutex
。 So, 所以,
while not mutex
Will constantly test the old value of that entry even after it is updated. 即使更新了该条目也将不断测试该条目的旧值。 You should iterate over the indices instead:
您应该改为遍历索引:
for i in range(len(exitmutexes)):
while not exitmutexes[i]: print(exitmutexes[i])
Alternatively, with enumerate
: 另外,用
enumerate
:
for i, mutex in enumerate(exitmutexes):
while not exitmutexes[i]: print(mutex)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.