Python 线程
大家好,我无法理解以下代码的某些部分(来自 Mark Lutz 的 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.')
Hey all, I'm unable to understand some part of the following code (from Programming Python by Mark Lutz):
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.')
I'm using Python3. Well, I'm able to understand the stdoutmutex thing and how it works, but I'm unable to understand how the above code processes exitmutexes list, because the individual locks in exitmutexes have been acquired, but not released. Once all the 10 threads have started, how do the below 3 lines work? The author has described this as a way of going without using time.sleep()
for mutex in exitmutexes:
while not mutex.locked(): pass
print('Main thread exiting.')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它基本上会等到所有退出互斥锁都被锁定然后退出。
此代码迭代退出互斥体,并且对于每个互斥体,它进入一个循环,等待互斥体被锁定。
然而,它使用“主动等待”,导致 CPU 使用率非常高(就像无限循环什么也不做),这是一件非常糟糕的事情。
It basically waits until all exit mutexes have been locked and then exits.
This code iterates over the exit mutexes and for each mutex it enters a loop waiting for the mutex to be locked.
However, it uses "active waiting" resulting in very high CPU usage (like an endless loop doing nothing) which is a very bad thing.