1

I was using this following example to try & figure out the multiprocessing module in Python, but then I started to wonder, what happens when you try & multiproccess on a single core CPU? What exactly would happen with this following example? I assume it would run, but what exactly would be happening under the hood?

import os
import random
import sys
import time
import multiprocessing
from multiprocessing import pool

if __name__ == '__main__':
def worker(number):
    sleep = random.randrange(1, 10)
    time.sleep(sleep)
    print("I am Worker {}, I slept for {} seconds".format(number, sleep))

for i in range(5):
    t = multiprocessing.Process(target=worker, args=(i,))
    t.start()

print("All Processes are queued, let's see when they finish!")
  • Your single cor will alternate between the different processes. I believe this alternance is done every 200ms but i'm not sure at all. You can look at https://www.quora.com/How-does-multithreading-work-in-a-single-core-computer – Maxouille Mar 12 '19 at 14:38
  • 1
    You would not notice performance improvements when executing this on single vs. multicore CPUs. But replace the `time.sleep` with doing some heavy calculations, and that will change drastically. – L3viathan Mar 12 '19 at 14:39

1 Answers1

3

One of the functions of the operating system is task scheduling. And that is exactly what would happen. All your threads would be added to the scheduler list and it would check on each task regularly and run each one for a short time. Since all your workers do is sleep, it would probably only check on them at the start and at the end (the system call for sleep tells the scheduler that the task is not going to need any processing for some time).

Mad Wombat
  • 14,490
  • 14
  • 73
  • 109