繁体   English   中英

变量在线程中更新,但更新后的值不反映在循环内

[英]Variable is updated in a thread but updated value does not reflect inside a loop

我正在研究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.')

上面的代码工作正常。 它为每个子线程使用互斥锁,并将它们添加到全局exitmutexes列表中。 在退出时,每个线程都通过打开其锁来向主线程发出信号。

我以为我可以使用一般的布尔标志,而不是allocate_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.')

我的版本不起作用。 它只是不断循环。 为什么简单的布尔标志在这里不起作用? 谢谢。

mutex是一个循环变量。 它接收到的值的快照exitmutexes[i]在第i 迭代,从而当exitmutexes[i]被更新时,变化不可见mutex 所以,

while not mutex

即使更新了该条目也将不断测试该条目的旧值。 您应该改为遍历索引:

for i in range(len(exitmutexes)):
    while not exitmutexes[i]: print(exitmutexes[i]) 

另外,用enumerate

for i, mutex in enumerate(exitmutexes):
    while not exitmutexes[i]: print(mutex)  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM