Wednesday, 13 October 2021

mutiprocessing with "spawn" context cannot access shared variables in Linux

I have to use the Process method with "spawn" context in Linux. Then I write a sample code as follows:

from multiprocessing import Value
import multiprocessing

class Test(object):
    def __init__(self, m_val):
        print("step1")
        self.m_val = m_val
        print("step2")
        self.m_val_val = m_val.value
        self.prints()
    def prints(self):
        print("self.m_val_val:%d"%self.m_val_val)


def main(m_val):
    t = Test(m_val)

if __name__   == "__main__":
    N = 2
    procs = []
    v = Value("i",10)
    for i in range(0,N):
        proc_i = multiprocessing.get_context("spawn").Process(target=main,args=(v,))
        proc_i.daemon=True
        procs.append(proc_i)
    for i in range(0,N):
        procs[i].start()
    
    for i in range(0,N):
        procs[i].join()

When I run this code in Linux, it will print:

step1
step2
step1
step2

while in Windows, the print content will be:

step1
step2
self.m_val_val:10
step1
step2
self.m_val_val:10

Besides, there is no error information printed on the screen. So, how can I solve this problem, i.e., how to use multiprocessing Value in among processes while using "spawn" context in Linux?



from mutiprocessing with "spawn" context cannot access shared variables in Linux

No comments:

Post a Comment