多线程共享全局变量以及由此带来的安全问题/day18
作者:互联网
由于每个进程有自己独立的存储空间,而多个线程之间共享进程的存储内容,所以会出现下面的结果
代码1:
#多线程可以共享全局变量
g_num=100 #全局变量
def work1():
global g_num
for i in range(3):
g_num=g_num+1
print("In work1 gnu_m is %d"%(g_num))
def work2():
global g_num
for i in range(3):
g_num=g_num+1
print("In work2 gnu_m is %d"%(g_num))
from threading import Thread
if __name__ == '__main__':
t1=Thread(target=work1) #创建线程
t1.start()
t2=Thread(target=work2)
t2.start()结果如下:
"""
In work1 gnu_m is 103
In work2 gnu_m is 106
"""
代码2:
#进程有自己独立的资源,不实现资源共享,
#多进程之间内存独立不能共享全局变量,如果通信的话用Queue队列
g_num=100 #全局变量
def work1():
global g_num
for i in range(3):
g_num=g_num+1
print("In work1 gnu_m is %d"%(g_num))
def work2():
global g_num
for i in range(3):
g_num=g_num+1
print("In work2 gnu_m is %d"%(g_num))
from multiprocessing import Process
if __name__ == '__main__':
t1=Process(target=work1)
t1.start()
t2=Process(target=work2)
t2.start()结果如下:
"""
In work2 gnu_m is 103
In work1 gnu_m is 103
"""
#优点:线程之间的数据交互变的简单
#缺点:线程可以对全局变量进行修改,可能会造成数据混乱,即线程是非安全的
标签:__,全局变量,gnu,num,work1,work2,多线程,day18 来源: https://blog.csdn.net/qq_39112101/article/details/88539223