运行结果:
—线程创建之前g_num is 0—
----in work1, g_num is 100—
----in work2, g_num is 200—
2个线程对同一个全局变量操作之后的最终结果是:200
乍一看,好像没出什么问题。那是因为数据太小了,我们现在把数据变大。
‘’’
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
‘’’
import threading
import time
g_num = 0
def work1(num):
global g_num
for i in range(num):
g_num += 1
print(“----in work1, g_num is %d—” % g_num)
def work2(num):
global g_num
for i in range(num):
g_num += 1
print(“----in work2, g_num is %d—” % g_num)
print(“—线程创建之前g_num is %d—” % g_num)
t1 = threading.Thread(target=work1, args=(1000000,))
t1.start()
t2 = threading.Thread(target=work2, args=(1000000,))
t2.start()