Advanced Python (8)—Global variables in processes and threads

Original link: https://chegva.com/5604.html

◎Knowledge points

  1. Global variables cannot be shared among multiple processes

  2. Global variables can be shared among all threads of a process


◎Script practice

 Global variables cannot be shared among multiple processes

 """ 
  
Each process has its own memory space, so the processes are independent of each other. Therefore, global variables cannot be shared among multiple processes. 
  
""" 
  
 
  
from multiprocessing import Process 
  
 
  
num = 18 
  
 
  
def do_sth(): 
  
global num 
  
num += 1 
  
 
  
if __name__ == '__main__': 
  
 
  
p = Process(target=do_sth) 
  
p. start() 
  
p. join() 
  
 
  
#Modifying global variables in the child process has no effect on the global variables in the parent process# Because the child process makes a copy of the global variables in the parent process, the num in the child process and the parent process are completely different variable print(num) #18 

Global variables can be shared among all threads of the process

 """ 
  
All threads in the process share memory space, so global variables can be shared among all threads of the process""" 
  
 
  
from threading import Thread 
  
 
  
num = 18 
  
 
  
def do_sth2(): 
  
global num 
  
num += 1 
  
 
  
if __name__ == '__main__': 
  
 
  
p = Thread(target=do_sth2) 
  
p. start() 
  
p. join() 
  
 
  
print(num) # 19 

全局变量在进程的所有线程中可以共享.png

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_senior/process(thread)_global_variable.py

This article is transferred from: https://chegva.com/5604.html
This site is only for collection, and the copyright belongs to the original author.