Raed Ali
Raed Ali

Reputation: 587

Start while loop in one multiprocessing function, from another multiprocessing function

So I want to start a nested while loop in one multiprocessing function from another multiprocessing function. In one function, I'm changing a variable (action) to "fn2", and in the other function there is a nested while loop whose condition is while action == "fn2":.

See code:

from multiprocessing import Process

running = True
action = None


def func1():
    global action
    if 1+1 == 2:
        action = "fn2"
        print(action)


def func2():
    while running:
        while action == "fn2":
            print("fn2")


if __name__ == '__main__':
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    p1.join()
    p2.join()

However, when I run it, the code just prints "fn2" once (confirming that action is equal to "fn2"). But the nested loop inside func2() does not execute. Sorry if the answer is obvious, I'm new to multiprocessing.

Upvotes: 1

Views: 1386

Answers (1)

darren
darren

Reputation: 5744

i added two comments (with print statements) to highlight the error.

basically action=None in func2() so that is why...

from multiprocessing import Process

running = True
action = None


def func1():
    global action
    if 1+1 == 2:
        action = "fn2"
        print(action)


def func2():
    while running:
        print('got here')  # <--- loops infinitly here
        print(action) # <--- this is none
        while action == "fn2":
            print("fn2")


if __name__ == '__main__':
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    p1.join()
    p2.join()

In order to share values when multiprocessing, which is called Sharing state between processes you need to use value or array for a single device shared memory or alternatively, Manager for networks of servers.

Here is a link: https://docs.python.org/3/library/multiprocessing.html

The basic format looks like this:

from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

So in the case of the question what the variable action is equivalent to n (variable) or a (list) etc.. and this can be shares across functions.

Also note that one can parse arguments into multiprocess functions with the args keyword: args=(num, arr ...).

Upvotes: 2

Related Questions