Created
April 7, 2023 19:58
-
-
Save ifndefJOSH/54660e72b14848cf905245b122d8dd57 to your computer and use it in GitHub Desktop.
Simple Multithreading example in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
''' | |
Simple multithreading demo. Written 4/7/23 by Josh Jeppson (ifndefJOSH). | |
No warranty is given or implied. This was written to show a coworker how to get started with multithreading in Python. | |
''' | |
import threading | |
from os import cpu_count | |
# This will allow someTask() to take varied amounts of time | |
# to complete, much like real-world multithreading problems | |
import random | |
from time import sleep | |
# Number of threads to create | |
# This creates as many as there are logical CPU cores | |
N_THREADS = cpu_count() | |
# This is the number of times the information in someTask() | |
# will print to the screen | |
PRINT_ITERATIONS = 5 | |
def someTask(n = 0): | |
''' | |
This is the function we will be running on multiple CPUs. Or rather, | |
this function will be run multiple times, once per CPU | |
''' | |
# Print hello world from our threads | |
for _ in range(PRINT_ITERATIONS): | |
sleep(random.random() * 2) # Each thread can wait 0-2 s before printing | |
print(f"Hello world from thread {n}") | |
if __name__=="__main__": | |
threads = [threading.Thread( | |
# Do not put the "()" at the end of the function name | |
# You want the function pointer, NOT an invocation of the | |
# function yet | |
target = someTask | |
# This is a tuple which allows you to specify the args to the function | |
, args = (n, ) | |
) for n in range(N_THREADS) | |
] | |
# Starts each of the threads in the array of threads | |
for thread in threads: | |
thread.start() | |
# Waits for each thread to finish. If you don't have this | |
# then the program stops and the threads do not finish. | |
# Also, this MUST be separate from the loop that starts them all | |
for thread in threads: | |
thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output (on a system with 8 logical cores):