Using Threading in python
What is threading
Threading refers to the process of executing multiple threads (also known as lightweight processes) concurrently within a single program. A thread is a sequential flow of control within a program, and each thread can run independently of other threads, allowing for the simultaneous execution of multiple tasks.
In Python, to run specific code in a thread, that code has to be in a function.
For example,
import time
def run():
time.sleep(1) # Heavy computation
print("Heavy computation completed")
Generally, this code may be some heavy task that we will want to complete so for this case, I will simulate that by waiting for 1 second.
Python comes with a built-in module that allows you to use threading without any installation.
import threading
To create a thread, we use the threading.Thread
function and it takes some arguments which I will be covering just three.
target
: The function to be run in the threadargs
: A tuple of arguments to be passed in that functiondaemon
: If is set toTrue
, the thread stops when the code exits (Whether the thread has finished or not)
import threading
import time
def run():
time.sleep(1) # Heavy computation
print("Heavy computation completed")
t = threading.Thread(target=run)
t.start()
print("Ended")
Output:
Ended
Heavy computation completed
If other variables like args
and daemon
are passed in, the code will look like this
def run(n):
import time
time.sleep(n) # Heavy computation
print("Heavy computation completed")
threading.Thread(target=run, args=(1,), daemon=True)
print("Ended")
Note: Make sure the args variable is a tuple
.
Output:
Ended
The "Heavy computation completed" was not printed because it didn't run before the code ended.
Conclusion
Python threading is a powerful tool for achieving concurrency and parallelism in our programs. By using the built-in threading
module, we can create and manage multiple threads that can execute simultaneously, improving program performance. With threading, we can create faster, more efficient programs that take full advantage of modern hardware.