Python 线程

发布于 2024-11-01 05:06:16 字数 949 浏览 0 评论 0原文

大家好,我无法理解以下代码的某些部分(来自 Mark LutzPython 编程):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

念﹏祤嫣 2024-11-08 05:06:16

它基本上会等到所有退出互斥锁都被锁定然后退出。

for mutex in exitmutexes:
    while not mutex.locked(): pass

此代码迭代退出互斥体,并且对于每个互斥体,它进入一个循环,等待互斥体被锁定。

然而,它使用“主动等待”,导致 CPU 使用率非常高(就像无限循环什么也不做),这是一件非常糟糕的事情。

It basically waits until all exit mutexes have been locked and then exits.

for mutex in exitmutexes:
    while not mutex.locked(): pass

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文