This is a basic overview of threading in python. All of the information can be found in the video below by Corey Schafer.
Threading is the process of running multiple pieces of code concurrently. Note that this is different from multiprocessing, which is running multiple pieces of code in parallel. Threading is used to increase the speed of your code. However, threading is NOT guaranteed to increase the speed of your code. Threading is used to improve the speed of IO bound tasks (tasks that require data to be used, often involve a lot of waiting) as opposed to tasks that are CPU bound (tasks that require a ot of data to be processed). Multiprocessing would be used to improve CPU bound tasks.
You can create threads manually as with the example below:
import threading
import time
start = time.perf_counter()
def do_something():
print(“Sleeping 1 second”)
time.sleep(1)
print(“Done Sleeping”)
t1 = threading.Thread(target=do_something)
t1 = threading.Thread(target=do_something)
t1.start()
t2.start()
finish = time.perf_counter()
print(f”Finished in {round(finish-start, 2)} seconds”)
You can also use a thread pool executor. A thread pool executor is a function used to create and execute multiple threads. it is extremely useful when making a large number of threads.
Here is an example of creating threads using a thread pool executor:
import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f’Sleeping {seconds} second(s)…’)
time.sleep(seconds)
return f’Done Sleeping…{seconds}’
with concurrent.futures.ThreadPoolExecutor() as executor:
secs = [5, 4, 3, 2, 1]
results = executor.map(do_something, secs)
Nice work. I like how you embedded the YouTube video. In future posts, consider using the “Code” block from WordPress to make your computer code stand out a little more.