Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel multiprocessing in python easy example

I need to say that multiprocessing is something new to me. I read some about it but it makes me more confused. I want to understand it on a simple example. Let's assume that we have 2 functions in first one I just increment 'a' variable and then assign it to 'number' variable, in second I start first function and each every one second I want to print 'number' variable. It should looks like:

global number

def what_number():
    a=1
    while True:
       a+=1
       number=a

def read_number():
    while True:
       --> #here I need to start 'what_number' function <--
        time.sleep(1)
        print(number)


if __name__ == "__main__":
    read_number()

How can I do that? Is there an easy and proper way to do that ?

UPDATE:

I saw noxdafox answer I'm really thankfull but it isn't exactly what I want. First of all I don't want send value in first function ('main' in noxdafox code). Second I don't want to get all values so quene will won't work. I need to get after each second number of while loops. Code should be something like :

import multiprocessing
import time

number = 0


def child_process():
    global number
    while True:
        number += 1
        print(number)


def main():
    process = multiprocessing.Process(target=child_process)
    process.start()

    while True:
       print("should get same number:",number)
       time.sleep(0.001)

if __name__ == "__main__":
    main()

If u run above code you get something like: enter image description here

but this blue selected values should be same ! and that's the main problem :)

P.S sorry for chaos

like image 254
KyluAce Avatar asked May 15 '26 05:05

KyluAce


1 Answers

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()
like image 194
KyluAce Avatar answered May 17 '26 19:05

KyluAce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!