Parallel multiprocessing in python easy example

故事扮演 提交于 2019-12-04 18:24:53

Ok it takes some time but I figured it out. All it was about Sharing state between processes now all it works like charm. Code :

from multiprocessing import Process, Value
import time


def child_process(number):
    number.value = 0
    while True:
        number.value += 1
        #print(number)


def main():
    num = Value('i')
    process = Process(target=child_process, args=(num,))
    process.start()
    while True:
       print("should get same number:", num.value)
       time.sleep(1)

if __name__ == "__main__":
    main()

As processes live in separate memory address spaces, you cannot share variables. Moreover, you are using global variables incorrectly. Here you can see an example on how to use global variables.

The most straightforward way to share information between processes is via a Pipe or Queue.

import multiprocessing

def child_process(queue):
    while True:
        number = queue.get()
        number += 1
        queue.put(number)

def main():
    number = 0
    queue = multiprocessing.Queue()
    process = multiprocessing.Process(target=child_process, args=[queue])
    process.start()

    while True:
        print("Sending %d" % number)
        queue.put(number)

        number = queue.get()
        print("Received %d" % number)

        time.sleep(1)

if __name__ == "__main__":
    main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!