Multi-process Cannot Share Global Variables | Teach You to Get Started With Python One Hundred and Six

Related Tags:1.ApsaraDB RDS for MySQL
2. Prototypes and Inheritance in JavaScript

Multi-process Cannot Share Global Variables | Teach You to Get Started With Python One Hundred and Six

Multi-process Cannot Share Global Variables.Two child threads in the same main process. Threads can share global variables of the same process, and different processes each save a global variable and do not share global variables.
Multiple processes cannot share global variables
import os , multiprocessing, threading

n = 100


def test () :
global n
n += 1
print( The value of n in 'test===={} is {}' .format( os.getpid (), hex(id(n))))


def demo () :
global n
n += 1
print( The value of n in 'demo===={} is {}' .format( os.getpid (), hex(id(n))))


print( threading.current_thread ().name)
test() # 101
demo() # 102

# Two child threads in the same main process. Threads can share global variables of the same process

# t1 = threading.Thread (target=test)
# t2 = threading.Thread (target=demo)
# t1.start()
# t2.start()

# if __name__ == '__main__':
# Each process saves a global variable and does not share global variables
# p1 = multiprocessing.Process (target=test)
# p2 = multiprocessing.Process (target=demo)
# p1.start() # 101
# p2.start() # 101
Example:
from multiprocessing import Process
import os

nums = [ 11 , 22 ]

def work1 () :
"""The code to be executed by the child process"""
print( "in process1 pid =%d , nums =%s" %( os.getpid (), nums ))
for i in range( 3 ):
nums.append ( i )
print( "in process1 pid =%d , nums =%s" %( os.getpid (), nums ))

def work2 () :
"""The code to be executed by the child process"""
nums.pop ()
print( "in process2 pid =%d , nums =%s" %( os.getpid (), nums ))

if __name__ == '__main__':
p1 = Process(target=work1)
p1.start()
p1.join()

p2 = Process(target=work2)
p2.start()

print('in process0 pid={} ,nums={}'.format(os.getpid(),nums))
运行结果:
in process1 pid=2707 ,nums=[11, 22]
in process1 pid=2707 ,nums=[11, 22, 0]
in process1 pid=2707 ,nums=[11, 22, 0, 1]
in process1 pid=2707 ,nums=[11, 22, 0, 1, 2]
in process0 pid=2706 ,nums=[11, 22]
in process2 pid=2708 ,nums=[11]

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us