user3403889
user3403889

Reputation: 3

Multiprocessing issues in python

This is a simple code to test multiprocessing in python. f() prints a couple of integers every seconds and monitor() prints a warning if the ourput of f() crosses a threshold.

#!/usr/bin/python
from multiprocessing import Process
import time

def f():
    global y
    n = 20
    for i in range (n):
        y = i
        print y
        time.sleep(1)

def monitor():
    n = 20
    for i in range(20):
        if y >= 10:
            print 'y is greater than 10.'
        time.sleep(1)

if __name__ == '__main__':
    p1 = Process(target = f, args = ())
    p2 = Process(target = monitor, args = ())
    p1.start()
    p2.start()
    p1.join()
    p2.join()

The problem is that nothing happens when I execute this code. I don't even get an error. How can I fix this? The same process works perfectly if I use threading instead of multiprocessing, but I'd like to be able to do the same stuff with multiprocessing too.

python v 2.7.6

OS: windows 7

Upvotes: 0

Views: 91

Answers (1)

ebarr
ebarr

Reputation: 7842

So I get errors when I run your code. These come from the fact that global y is not shared between processes. You must explicitly set aside shared memory for interprocess communication when using the multiprocessing package. You can do this using a synchronised Value instance.

So your code should be:

#!/usr/bin/python                                                                                                                                                                      
from multiprocessing import Process,Value
import time
import ctypes

def f(y):
    n = 20
    for i in range (n):
        y.value = i
        print y.value
        time.sleep(1)

def monitor(y):
    n = 20
    for i in range(20):
        if y.value >= 10:
            print 'y is greater than 10.'
        time.sleep(1)

if __name__ == '__main__':
    y = Value(ctypes.c_int)
    p1 = Process(target = f, args = (y,))
    p2 = Process(target = monitor, args = (y,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

Upvotes: 1

Related Questions