线程共享全局变量

  • 在一个进程内所有线程共享全局变量,多线程之间的数据共享比多进程要好。但是可能造成多个进程同时修改一个变量(即线程非安全),可能造成混乱。

  •  1 import time
     2 from threading import *
     3 #定义全局变量num
     4 num=10
     5 def test1():
     6     global num
     7     for i in range(3):
     8         num+=1
     9     print('test1输出num:',num)
    10 
    11 def test2():
    12     global num
    13     print('test2输出num:',num)
    14 
    15 if __name__=='__main__':
    16     t1=Thread(target=test1)
    17     t2=Thread(target=test2)
    18     t1.start()
    19     t1.join()
    20     t2.start()
    21     t2.join()
    1 test1输出num: 13
    2 test2输出num: 13

猜你喜欢

转载自www.cnblogs.com/monsterhy123/p/12682605.html
今日推荐