December 2018
Beginner to intermediate
796 pages
19h 54m
English
Just for fun, let's play with two threads now:
# starwars.pyimport threadingfrom time import sleepfrom random import randomdef 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 ...
Read now
Unlock full access