+ =运算符在Python中是线程安全的吗? [英] Is the += operator thread-safe in Python?
本文介绍了+ =运算符在Python中是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个非线程安全的代码块进行实验,这些是2个线程将要调用的函数.
I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
c = 0
def increment():
c += 1
def decrement():
c -= 1
此代码线程安全吗?
如果没有,我可以理解为什么它不是线程安全的,以及哪种类型的语句通常会导致非线程安全的操作.
If not, may I understand why it is not thread safe, and what kind of statements usually lead to non-thread-safe operations.
如果它是线程安全的,如何使它显式地成为非线程安全的?
If it is thread-safe, how can I make it explicitly non-thread-safe?
推荐答案
由于GIL,单个操作码是线程安全的,但除此之外:
Single opcodes are thread-safe because of the GIL but nothing else:
import time
class something(object):
def __init__(self,c):
self.c=c
def inc(self):
new = self.c+1
# if the thread is interrupted by another inc() call its result is wrong
time.sleep(0.001) # sleep makes the os continue another thread
self.c = new
x = something(0)
import threading
for _ in range(10000):
threading.Thread(target=x.inc).start()
print x.c # ~900 here, instead of 10000
由多个线程共享的每个资源必须具有锁定.
这篇关于+ =运算符在Python中是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文