我想测试是否可以从两个线程追加到列表,但我得到了混乱的输出:
import threading
class myThread(threading.Thread):
def __init__(self, name, alist):
threading.Thread.__init__(self)
self.alist = alist
def run(self):
print "Starting " + self.name
append_to_list(self.alist, 2)
print "Exiting " + self.name
print self.alist
def append_to_list(alist, counter):
while counter:
alist.append(alist[-1]+1)
counter -= 1
alist = [1, 2]
# Create new threads
thread1 = myThread("Thread-1", alist)
thread2 = myThread("Thread-2", alist)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
print alist
所以输出是:
Starting Thread-1
Exiting Thread-1
Starting Thread-2
Exiting Main Thread
Exiting Thread-2
[1[1, 2[, 1, 2, 23, , 34, 5, 6, ]4
, 5, , 3, 64, 5, ]6]
为什么这么乱,alist不等于[1,2,3,4,5,6]?
原文由 Alexey 发布,翻译遵循 CC BY-SA 4.0 许可协议
编辑:@kroltan 让我多想了一些,我认为你的例子实际上比我最初想的更线程安全。问题完全不在多个编写器线程中,特别是在这一行中:
不能保证
append
会在alist[-1]
完成后直接发生,其他操作可能会交错。这里有详细的解释:http: //effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm
原答案: