Python multiprocessing class methods -


i'm trying change class field using it's method, when method put doesn't work.

from multiprocessing import process

class multi:     def __init__(self):         self.x = 20       def loop(self,):         in range(1,100):             self.x =  m = multi()  p = process(target=m.loop) p.start() 

after running program m.x still 20. how possible?

first, want use join, waits process finish before continuing through rest of code.

second, when use multiprocess, creates new instance of m every process. can see when printing self within loop

class multi:     def __init__(self):         self.x = 20      def loop(self):         print(self, 'loop')         in range(1, 100):             self.x =   if __name__ == '__main__':     m = multi()     print(m, 'main 1')     p = process(target=m.loop)     p.start()     p.join()     print(m, 'main 2')  >>> <__main__.multi object @ 0x000001e19015ccc0> main 1 >>> <__mp_main__.multi object @ 0x00000246b3614e10> loop >>> <__main__.multi object @ 0x000001e19015ccc0> main 2 

because of that, value of x never updated in original class.

fortunately, there value object can use handles this. creates shared memory object can modified through processes

from multiprocessing import process, value   class multi:     def __init__(self):         self.x = value('i', 20)      def loop(self):         in range(1, 100):             self.x.value =   if __name__ == '__main__':     m = multi()     p = process(target=m.loop)     p.start()     p.join()      print(int(m.x.value))     >> 99 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -