There are a few ways to achieve this:
multiprocessing.Manager()
class:from multiprocessing import Pool, Manager
global_var = None
def func(x):
global global_var
global_var += x
if __name__ == '__main__':
global_var = 0
with Manager() as manager:
global_var = manager.Value('i', global_var)
p = Pool()
p.map(func, [1, 2, 3])
p.close()
p.join()
print(global_var.value)
In this example, the Manager()
class is used to create a shared variable global_var
. The variable is passed to the function as an argument and can be accessed like any other shared variable.
multiprocessing.sharedctypes
module:from multiprocessing import Pool, sharedctypes, RawArray
global_var = None
def func(x):
global global_var
global_var[0] += x
if __name__ == '__main__':
global_var = RawArray('i', [0])
global_var = sharedctypes.RawArray('i', global_var)
p = Pool()
p.map(func, [1, 2, 3])
p.close()
p.join()
print(global_var[0])
In this example, a RawArray
object is created and then converted into a shared ctypes object. The shared variable is accessed by indexing the shared array.
Note: It is important to note that changes made to global variables in one process will not affect the values of the same variable in other processes. Therefore, the global variable should be shared among all the processes using one of the methods described above.
Asked: 2023-06-22 11:10:35 +0000
Seen: 17 times
Last updated: Jun 22 '23