import threading counter = 0 def increment(): global counter for _ in range(1000000): counter += 1 threads = [threading.Thread(target=increment) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() print(counter)
import threading counter = 0 def increment(): global counter for _ in range(1000000): counter += 1 threads = [threading.Thread(target=increment) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() print(counter)
始终打印2000000,因为GIL保证线程安全
结果不确定,可能小于2000000,因为counter += 1不是原子操作
结果不确定,可能大于2000000
会抛出RuntimeError

这道题你会答吗?花几分钟告诉大家答案吧!