天天看點

多線程共享全局變量

1.子線程,主線程共享全局變量

1 import threading                                       
  2 import time
  3 
  4 num=100
  5 
  6 def test1():
  7     global num
  8     num+=100
  9     print("-----test1----num:%s"%num)
 10 
 11 
 12 def test2():
 13     print("-----test2----num:%s"%num)
 14 
 15 
 16 def main():
 17     t1=threading.Thread(target=test1)
 18     t2=threading.Thread(target=test2)
 19     t1.start()
 20     time.sleep(1)
 21     
 22     t2.start()
 23     time.sleep(1)
 24 
 25     print("----main----num:%s"%num)
 26 
 27 
 28 if __name__=="__main__":
 29     main()
           

代碼執行結果:

-----test1----num:200
-----test2----num:200
----main----num:200

           

2.args傳遞參數

1 import threading                                       
  2 import time
  3 
  4 num=[11,22]
  5 
  6 def test1(temp):
  7     temp.append(33)
  8     print("-----test1----temp:%s"%temp)
  9 
 10 
 11 def test2(temp):
 12     print("-----test2----temp:%s"%temp)
 13 
 14 
 15 def main():
 16     #target指定線程将來去哪個函數執行代碼
 17     #args必須是元組,指定調用函數時,傳遞的參數
 18     t1=threading.Thread(target=test1,args=(num,))
 19     t2=threading.Thread(target=test2,args=(num,))
 20     t1.start()
 21     time.sleep(1)
 22     
 23     t2.start()
 24     time.sleep(1)
 25 
 26     print("----main----temp:%s"%num)
 27 
 28 
 29 if __name__=="__main__":
 30     main()

           

執行結果

-----test1----temp:[11, 22, 33]
-----test2----temp:[11, 22, 33]
----main----temp:[11, 22, 33]

           

繼續閱讀