callFromThread线程是否安全

时间:2011-06-30 22:51:54

标签: thread-safety twisted

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

1 个答案:

答案 0 :(得分:2)

多个线程可以向列表添加项目(这些是生产者),并且它总是通过 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.