Spawning multiple threads

Just for fun, let's play with two threads now:

# starwars.py
import threading
from time import sleep
from random import random

def run(n):
t = threading.current_thread()
for count in range(n):
print(f'Hello from {t.name}! ({count})')
sleep(0.2 * random())

obi = threading.Thread(target=run, name='Obi-Wan', args=(4, ))
ani = threading.Thread(target=run, name='Anakin', args=(3, ))
obi.start()
ani.start()
obi.join()
ani.join()

The run function simply prints the current thread, and then enters a loop of n cycles, in which it prints a greeting message, and sleeps for a random amount of time, between 0 and 0.2 seconds (random() returns a float between 0 and 1).

The purpose of this example is to show you how a scheduler might jump between threads, so it helps to make them sleep a little. Let's see the output:

$ python starwars.py
Hello from Obi-Wan! (0)
Hello from Anakin! (0)
Hello from Obi-Wan! (1)
Hello from Obi-Wan! (2)
Hello from Anakin! (1)
Hello from Obi-Wan! (3)
Hello from Anakin! (2)

As you can see, the output alternates randomly between the two. Every time that happens, you know a context switch has been performed by the scheduler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset