Python | Multiple processes cannot share global variables

Multiple processes cannot share global variables


import os, multiprocessing, threading

n = 100


def test():
global n
n += 1
print('test==={} the value of n 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))
operation result:

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