- Programming technique known as multithreading enables numerous threads to execute concurrently within a single programme.
- Multithreading in Python refers to the capability of executing numerous threads simultaneously within a single Python application.
- Each thread has its own memory area, context, and ability to function independently of other threads within the same application. Tasks can be carried out in parallel as a result, which may enhance performance and responsiveness.
- The threading module in Python offers the essential features for using threads. To construct and manage threads, utilise the Thread class from this module. The Thread class is instantiated to construct each thread, and the target function and any parameters for that function are passed along with it.
Here’s a Python multithreading tutorial using a car example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import threading import time def print_make_model(make, model): print(f"{make} {model}") time.sleep(2) # List of cars cars = [("Toyota", "Corolla"), ("Honda", "Civic"), ("Ford", "Mustang"), ("Chevrolet", "Camaro"), ("Nissan", "GT-R")] # Create a list of threads threads = [] for make, model in cars: # Create a new thread for each car t = threading.Thread(target=print_make_model, args=(make, model)) threads.append(t) # Start all the threads for t in threads: t.start() # Wait for all the threads to finish for t in threads: t.join() |
In this example, we have a list of cars, each with a make and a model. The print_make_model
function is a simple function that takes a make and a model and prints it.
We then create a list of threads, where each thread is created for each car. The threading.Thread
constructor takes the target
argument, which is the function that the thread will run, and the args
argument, which is a tuple of arguments to pass to the function.
Once the threads are created, we start them all using the start
method. Then, we use the join
method to wait for all the threads to finish.
With this code, each car’s make and model is printed in parallel, and the total time to print all the cars is about 2 seconds, which is the sleep time of each thread. Without multithreading, the total time would have been 10 seconds, one for each car.
Here’s a table of commonly used methods in the Python threading
module:
Method | Description | Syntax |
---|---|---|
start() | Starts the thread’s activity. | thread.start() |
run() | The method that is called when the thread is started. This method must be overridden in a subclass. | thread.run() |
join([timeout]) | Blocks the calling thread until the thread represented by this method terminates or until the optional timeout period is exceeded. | thread.join([timeout]) |
is_alive() | Returns True if the thread is running and False otherwise. | thread.is_alive() |
getName() | Returns the name of the thread. | thread.getName() |
setName(name) | Changes the name of the thread. | thread.setName(name) |
More common used methods below:
Method | Description | Syntax |
---|---|---|
active_count() | Returns the number of thread objects that are active. | threading.active_count() |
enumerate() | Returns a list of all thread objects that are currently executing. | threading.enumerate() |
current_thread() | Returns the current thread object, representing the caller’s thread of control. | threading.current_thread() |
Lock | A lock is used to synchronize access to a shared resource. A lock can be in one of two states: locked or unlocked. | lock = threading.Lock() |
RLock | A reentrant lock, or RLock, is a synchronization primitive that allows multiple calls to acquire() and release() by the same thread. | rlock = threading.RLock() |
Semaphore | A semaphore is used to control access to a shared resource. It can be thought of as a lock with a counter. | semaphore = threading.Semaphore(value) |
These methods provide additional tools for managing and synchronizing threads, and can be used to build more complex and sophisticated multithreaded applications.