Home > Backend Development > Python Tutorial > Implementation code for Python multi-threaded shared global variables

Implementation code for Python multi-threaded shared global variables

不言
Release: 2018-09-11 16:18:31
Original
2081 people have browsed it

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.

Example: Verify that all threads in the same process share global variables

Code:
#验证同一个进程内的所有线程共享全局变量
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()
Copy after login
Result:
start---num: 1000
work1----num: 1003
work2---num: 1003
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template