callFromThread 是线程安全的

发布于 2024-11-17 21:18:24 字数 177 浏览 1 评论 0原文

我查看了 callFromThread 的代码。它将所有可调用对象附加到 threadCallQueue 列表中。如果多个线程调用callFromThread,callFromThread怎么能是线程安全的呢?换句话说,如果没有threadCallQueue的锁,callFromThread怎么能是线程安全的呢?我错过了一些基本的东西吗?

I looked at the code for callFromThread. It's appending all the callables into threadCallQueue list. If multiple threads call callFromThread, how can callFromThread be thread-safe? In other words, without a lock on threadCallQueue, how can callFromThread be threadsafe? Am I missing something basic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

我早已燃尽 2024-11-24 21:18:24

多个线程可以将项目添加到列表中(这些是生产者),并且始终通过 append() 调用来完成(因此,在列表的末尾):

self.threadCallQueue.append((f, args, kw))

只有主线程会读取项目并从列表中删除它们(这个是消费者)并且它总是从列表的开头读取:

# Keep track of how many calls we actually make, as we're
# making them, in case another call is added to the queue
# while we're in this loop.
count = 0
total = len(self.threadCallQueue)
for (f, a, kw) in self.threadCallQueue:
    try:
        f(*a, **kw)
    except:
        log.err()
    count += 1
    if count == total:
        break
del self.threadCallQueue[:count]

因此,由于一个线程从列表的开头读取而其他线程在末尾写入,所以这是线程安全的只要 Python 列表是。该函数的源代码中对此进行了注释:

# lists are thread-safe in CPython, but not in Jython
# this is probably a bug in Jython, but until fixed this code
# won't work in Jython.

Multiple threads can add items to the list (these are the producers) and it's always done through an append() call (so, at the end of the list):

self.threadCallQueue.append((f, args, kw))

Only the main thread ever reads items and removes them from the list (this one is the consumer) and it always reads at the beginning of the list:

# Keep track of how many calls we actually make, as we're
# making them, in case another call is added to the queue
# while we're in this loop.
count = 0
total = len(self.threadCallQueue)
for (f, a, kw) in self.threadCallQueue:
    try:
        f(*a, **kw)
    except:
        log.err()
    count += 1
    if count == total:
        break
del self.threadCallQueue[:count]

So, since one thread reads from the beginning of the list and others write at the end, this is thread-safe as long as Python lists are. This is noted in the function's source code:

# lists are thread-safe in CPython, but not in Jython
# this is probably a bug in Jython, but until fixed this code
# won't work in Jython.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文