Python – Multithreading
Source: https://www.programiz.com/python-programming/time/sleep
Multithreading in Python
Before talking about sleep()
in multithreaded programs, let’s talk about processes and threads.
A computer program is a collection of instructions. A process is the execution of those instructions.
A thread is a subset of the process. A process can have one or more threads.
Example: Python multithreading
All the programs above in this article are single-threaded programs. Here’s an example of a multithreaded Python program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import threading def print_hello_three_times(): for i in range(3): print("Hello") def print_hi_three_times(): for i in range(3): print("Hi") t1 = threading.Thread(target=print_hello_three_times) t2 = threading.Thread(target=print_hi_three_times) t1.start() t2.start() |
1 2 3 4 5 6 |
Hello Hello Hi Hello Hi Hi |
The above program has two threads t1 and t2. These threads are run using t1.start()
and t2.start()
statements.
Note that, t1 and t2 run concurrently and you might get different output.
Visit this page to learn more about Multithreading in Python.
time.sleep() in multithreaded programs
The sleep()
function suspends execution of the current thread for a given number of seconds.
In case of single-threaded programs, sleep()
suspends execution of the thread and process. However, the function suspends a thread rather than the whole process in multithreaded programs.
Example: sleep() in a multithreaded program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import threading import time def print_hello(): for i in range(4): time.sleep(0.5) print("Hello") def print_hi(): for i in range(4): time.sleep(0.7) print("Hi") t1 = threading.Thread(target=print_hello) t2 = threading.Thread(target=print_hi) t1.start() t2.start() |
The above program has two threads. We have used time.sleep(0.5)
and time.sleep(0.75)
to suspend execution of these two threads for 0.5 seconds and 0.7 seconds respectively.