I am running the following code. I was expecting the prints would be random between the processes. However, I see a deterministic result: on each run, first of all the first process is finishing it's loop, and only then, the second process starts to run the loop. I was expecting for a random behaviour, which means context switches between the 2 processes. But all I see is after one process is finished, the second one starts, without any context switches.
Can someone describe what am I missing?
import multiprocessing
import time
import os
lock = multiprocessing.Lock()
def func(_lock):
for _ in range(0, 3):
with _lock:
print("sleeping in pid " + str(os.getpid()))
time.sleep(1)
print("finished sleeping in pid " + str(os.getpid()))
process1 = multiprocessing.Process(target=func, args=(lock,))
process2 = multiprocessing.Process(target=func, args=(lock,))
process1.start()
process2.start()
=============================================================
the output is:
sleeping in pid 2322
finished sleeping in pid 2322
sleeping in pid 2322
finished sleeping in pid 2322
sleeping in pid 2322
finished sleeping in pid 2322
sleeping in pid 2323
finished sleeping in pid 2323
sleeping in pid 2323
finished sleeping in pid 2323
sleeping in pid 2323
finished sleeping in pid 2323
Process finished with exit code 0