Creating a thread in Python involves initiating a separate flow of execution within a program, allowing multiple operations to run concurrently. This is particularly useful for performing tasks simultaneously, such as handling various I/O operations in parallel.
Python provides multiple ways to create and manage threads.
- Creating a thread using the threading module is generally recommended due to its higher-level interface and additional functionalities.
- On the other hand, the _thread module offers a simpler, lower-level approach to create and manage threads, which can be useful for straightforward, low-overhead threading tasks.
In this tutorial, you will learn the basics of creating threads in Python using different approaches. We will cover creating threads using functions, extending the Thread class from the threading module, and utilizing the _thread module.
Creating Threads with Functions
You can create threads by using the Thread class from the threading module. In this approach, you can create a thread by simply passing a function to the Thread object. Here are the steps to start a new thread −
- Define a function that you want the thread to execute.
- Create a Thread object using the Thread class, passing the target function and its arguments.
- Call the start method on the Thread object to begin execution.
- Optionally, call the join method to wait for the thread to complete before proceeding.
Example
The following example demonstrates concurrent execution using threads in Python. It creates and starts multiple threads that execute different tasks concurrently by specifying user-defined functions as targets within the Thread class.
Open Compiler
from threading import Thread
defaddition_of_numbers(x, y):
result = x + y
print('Addition of {} + {} = {}'.format(x, y, result))defcube_number(i):
result = i **3print('Cube of {} = {}'.format(i, result))defbasic_function():print("Basic function is running concurrently...")
Thread(target=addition_of_numbers, args=(2,4)).start()
Thread(target=cube_number, args=(4,)).start()
Thread(target=basic_function).start()
On executing the above program, it will produces the following result −
Addition of 2 + 4 = 6
Cube of 4 = 64
Basic function is running concurrently...
Creating Threads by Extending the Thread Class
Another approach to creating a thread is by extending the Thread class. This approach involves defining a new class that inherits from Thread and overriding its __init__ and run methods. Here are the steps to start a new thread −
- Define a new subclass of the Thread class.
- Override the __init__ method to add additional arguments.
- Override the run method to implement the thread’s behavior.
Example
This example demonstrates how to create and manage multiple threads using a custom MyThread class that extends the threading.Thread class in Python.
Open Compiler
import threading
import time
exitFlag =0classmyThread(threading.Thread):def__init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
defrun(self):print("Starting "+ self.name)
print_time(self.name,5, self.counter)print("Exiting "+ self.name)defprint_time(threadName, counter, delay):while counter:if exitFlag:
threadName.exit()
time.sleep(delay)print("%s: %s"%(threadName, time.ctime(time.time())))
counter -=1# Create new threads
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",2)# Start new Threads
thread1.start()
thread2.start()print("Exiting Main Thread")
When the above code is executed, it produces the following result −
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Mon Jun 24 16:38:10 2024
Thread-2: Mon Jun 24 16:38:11 2024
Thread-1: Mon Jun 24 16:38:11 2024
Thread-1: Mon Jun 24 16:38:12 2024
Thread-2: Mon Jun 24 16:38:13 2024
Thread-1: Mon Jun 24 16:38:13 2024
Thread-1: Mon Jun 24 16:38:14 2024
Exiting Thread-1
Thread-2: Mon Jun 24 16:38:15 2024
Thread-2: Mon Jun 24 16:38:17 2024
Thread-2: Mon Jun 24 16:38:19 2024
Exiting Thread-2
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
Creating Threads using start_new_thread() Function
The start_new_thread() function included in the _thread module is used to create a new thread in the running program. This module offers a low-level approach to threading. It is simpler but does not have some of the advanced features provided by the threading module.
Here is the syntax of the _thread.start_new_thread() Function
_thread.start_new_thread ( function, args[, kwargs])
This function starts a new thread and returns its identifier. The function parameter specifies the function that the new thread will execute. Any arguments required by this function can be passed using args and kwargs.
Example
import _thread
import time
# Define a function for the threaddefthread_task( threadName, delay):for count inrange(1,6):
time.sleep(delay)print("Thread name: {} Count: {}".format( threadName, count ))# Create two threads as followstry:
_thread.start_new_thread( thread_task,("Thread-1",2,))
_thread.start_new_thread( thread_task,("Thread-2",4,))except:print("Error: unable to start thread")whileTrue:pass
thread_task("test",0.3)
It will produce the following output −
Thread name: Thread-1 Count: 1
Thread name: Thread-2 Count: 1
Thread name: Thread-1 Count: 2
Thread name: Thread-1 Count: 3
Thread name: Thread-2 Count: 2
Thread name: Thread-1 Count: 4
Thread name: Thread-1 Count: 5
Thread name: Thread-2 Count: 3
Thread name: Thread-2 Count: 4
Thread name: Thread-2 Count: 5
Traceback (most recent call last):
File "C:\Users\user\example.py", line 17, in <module>
while True:
KeyboardInterrupt
The program goes in an infinite loop. You will have to press ctrl-c to stop.
Leave a Reply