Home > Article > Backend Development > Implementation code for Python multi-threaded shared global variables
The content of this article is about the implementation code of Python multi-threaded shared global variables. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Global variables are shared by all threads in a process. But multi-threaded changes to global variables can cause variable values to get messed up.
#验证同一个进程内的所有线程共享全局变量 from threading import Thread import time g_num=1000 def work1(): global g_num g_num+=3 print("work1----num:",g_num) def work2(): global g_num print("work2---num:",g_num) if __name__ == '__main__': print("start---num:",g_num) t1=Thread(target=work1) t1.start() #故意停顿一秒,以保证线程1执行完成 time.sleep(1) t2=Thread(target=work2) t2.start()
start---num: 1000 work1----num: 1003 work2---num: 1003
Related recommendations :
Sharing and releasing issues of python class variables under multi-threading
Explore the sharing issues of variables between threads in Python multi-process programming
The above is the detailed content of Implementation code for Python multi-threaded shared global variables. For more information, please follow other related articles on the PHP Chinese website!