Try doing it like this:
import multiprocessing
def smile_detection(thread_name, counter, lock):
for x in range(10):
with lock:
counter.value +=1
print thread_name, counter.value
count = multiprocessing.Value('i', 0)
lock = multiprocessing.Lock()
x = multiprocessing.Process(target=smile_detection, args=("Thread1", count, lock))
y = multiprocessing.Process(target=smile_detection, args=("Thread2", count, lock))
x.start()
y.start()
x.join()
y.join()
First problem is that global variables are not shared between processes. You need to use a mechanism with some type of threadsafe locking or synchronization. We can use multiprocessing.Value('i', 0)
to create a threadsafe, synchronized integer value. We use our multiprocessing.Lock()
to ensure that only one thread can update the counter at a time.
If you really want to use the global variable, you can use multiprocessing.Manager()
, which can stay in a global variable:
import multiprocessing
count = multiprocessing.Manager().Value('i', 0)
lock = multiprocessing.Manager().Lock()
def smile_detection(thread_name):
global count, lock
for x in range(10):
with lock:
counter.value +=1
print thread_name, counter.value
x = multiprocessing.Process(target=smile_detection, args=("Thread1",))
y = multiprocessing.Process(target=smile_detection, args=("Thread2",))
x.start()
y.start()
x.join()
y.join()
But, personally, I like the first method better, as a Manager()
overcomplicates this.
Here's the output now:
$ python test.py
Thread1 1
Thread1 2
Thread1 3
Thread1 4
Thread1 5
Thread1 6
Thread1 7
Thread1 8
Thread1 9
...
Thread2 15
Thread2 16
Thread2 17
Thread2 18
Thread2 19
Thread2 20