例:假设两个线程t1和t2都要对num=0进行增1运算,t1和t2都各对num修改10次,num的最终的结果应该为20。
但是由于是多线程访问,有可能出现下面情况:
在num=0时,t1取得num=0。此时系统把t1调度为”sleeping”状态,把t2转换为”running”状态,t2也获得num=0。
然后t2对得到的值进行加1并赋给num,使得num=1。然后系统又把t2调度为”sleeping”,把t1转为”running”。
线程t1又把它之前得到的0加1后赋值给num。这样,明明t1和t2都完成了1次加1工作,但结果仍然是num=1
1.g_num的值大部分是在一百万到两百万之间的情况
from threading import Thread
g_num = 0
def test1():
global g_num
for i in range(1000000):
# g_num += 1
b = g_num + 1
g_num = b
print("---test1---g_num=%d"%g_num)
def test2():
global g_num
for i in range(1000000):
a = g_num + 1
g_num = a
print("---test2---g_num=%d"%g_num)
if __name__ == '__main__':
p1 = Thread(target=test1)
p1.start()
p2 = Thread(target=test2)
p2.start()
#--------------------运行结果------------------------
---test1---g_num=1283303
---test2---g_num=1257613
Process finished with exit code 0
以上结果多个线程对同一资源的访问,对数据造成破坏,使得线程运行的结果不可预期。这种现象称为“线程不安全”
2.g_num的值小于一百万的情况
from threading import Thread
import time
g_num = 0
def test1():
global g_num
for i in range(1000000):
# g_num += 1
b = g_num + 1
time.sleep(0.1) #此处添加阻塞状态,是为了让b结果没有赋值给g_num就被切换到另一个函数
g_num = b
print("---test1---g_num=%d"%g_num)
def test2():
global g_num
for i in range(1000000):
a = g_num + 1
g_num = a
print("---test2---g_num=%d"%g_num)
if __name__ == '__main__':
p1 = Thread(target=test1)
p1.start()
p2 = Thread(target=test2)
p2.start()
#--------------------运行结果------------------------
---test2---g_num=27712
注:此结果没有出现 Process finished这句话的原因是sleep 0.1 秒 还要运行几十万次以上,
时间太长,所以程序 test1 其实一直在运行,只能强制停止程序。
跟第一个例子一样,线程不安全
3.正常情况g_num
from threading import Thread
import time
g_num = 0
def test1():
global g_num
for i in range(1000000):
# g_num += 1
b = g_num + 1
g_num = b
print("---test1---g_num=%d"%g_num)
def test2():
global g_num
for i in range(1000000):
a = g_num + 1
g_num = a
print("---test2---g_num=%d"%g_num)
if __name__ == '__main__':
p1 = Thread(target=test1)
p1.start()
time.sleep(1) #此处阻塞1秒,给test1充分运行时间,直至该线程运行结束
p2 = Thread(target=test2)
p2.start()
#--------------------运行结果------------------------
---test1---g_num=1000000
---test2---g_num=2000000
Process finished with exit code 0
本应该输出的g_num正确值
4.解决办法
from threading import Thread,Lock
g_num = 0
my_lock = Lock()
def test1():
global g_num
if my_lock.acquire(): #同步锁防止争夺资源
for i in range(1000000):
g_num = g_num+1
my_lock.release() #解锁
print("---test1---g_num=%d"%g_num)
def test2():
global g_num
if my_lock.acquire():
for i in range(1000000):
g_num = g_num+1
my_lock.release()
print("---test2---g_num=%d"%g_num)
if __name__ == '__main__':
p1 = Thread(target=test1)
p1.start()
p2 = Thread(target=test2)
p2.start()
#--------------------运行结果------------------------
---test1---g_num=1000000
---test2---g_num=2000000