I have been playing with multiprocessing, and I am trying to understand how it works and how to run code in parallel. For this, I created the following very trivial script:
import multiprocessing
import time
def write_something(text="Hi mum!", duration=60, interval=1):
time_end = time.time() + duration
while time.time() < time_end:
time.sleep(interval)
print(text)
def multiprocessing_process():
process1 = multiprocessing.Process(target=write_something(text="Hi mum!", duration=20, interval=10))
process2 = multiprocessing.Process(target=write_something(text="Hi dad!", duration=20, interval=5))
process1.start()
process2.start()
process1.join()
process2.join()
def main():
multiprocessing_process()
#multiprocessing_pool()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
main()
Based on what I've been reading, I was expecting the code to run on parallel, but the console output was:
Hi mum!
Hi mum!
Hi dad!
Hi dad!
Hi dad!
Hi dad!
While I was expecting something more like this:
Hi dad!
Hi dad!
Hi mum!
Hi dad!
Hi mum!
Hi dad!
I managed to observe this result by using multiprocessing.Pool and async_apply. But I don't understand why it doesn't work that way with multiprocessing.Process. I thought it was supposed to created 2 processes that run independently. What am I missing?