多线程-共享全局变量问题
多线程可能遇到的问题
假设有两个线程t1和t2,都要对一个变量g_num进行运算(+1),两个线程t1和t2分别对g_num各加10次,g_num的最终结果。
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)
def work2(num):
global g_num
for i in range(num):
g_num += 1
print('in work2:', g_num)
print('---线程创建之前:%d' % g_num)
t1 = threading.Thread(target=work1,args=(10,))
t2 = threading.Thread(target=work2,args= (10,))
t1.start()
t2.start()
while len(threading.enumerate())!=1:
time.sleep(
版权声明:本文为xingyan98原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。