Summary: in this tutorial, you’ll learn how to use the Python threading module to develop multi-threaded applications.
Single-threaded applications #
Let’s start with a simple program:
from time import sleep, perf_counter
def task():
print('Starting a task...')
sleep(1)
print('done')
start_time = perf_counter()
task()
task()
end_time = perf_counter()
print(f'It took {end_time- start_time: 0.2f} second(s) to complete.')
Code language: Python (python)How it works.
First, import the sleep() and perf_counter() functions from the time module:
from time import sleep, perf_counterCode language: Python (python)Second, define a function that takes one second to complete:
def task():
print('Starting a task...')
sleep(1)
print('done')Code language: Python (python)Third, get the value of the performance counter by calling the perf_counter() function:
start_time = perf_counter() Code language: Python (python)Fourth, call the task() function twice:
task()
task()Code language: Python (python)Fifth, get the value of the performance counter by calling the perf_counter() function:
end_time = perf_counter()Code language: Python (python)Finally, output the time that takes to complete running the task() function twice:
print(f'It took {end_time- start_time: 0.2f} second(s) to complete.')Code language: Python (python)Here is the output:
Starting a task...
done
Starting a task...
done
It took 2.00 second(s) to complete.Code language: Python (python)As you may expect, the program takes about two seconds to complete. If you call the task() function 10 times, it would take about 10 seconds to complete.
The following diagram illustrates how the program works: