How to create a new thread in Python
Published on Aug. 22, 2023, 12:15 p.m.
To create a new thread in Python, you can use the threading
module, which allows you to create and manage threads in a high-level way. Here is an example of how to create a new thread in Python:
import threading
def my_function():
print("Starting my_function")
# Your code here
print("Ending my_function")
thread = threading.Thread(target=my_function)
thread.start()
print("Thread started")
In this example, a new thread is created by creating an instance of the Thread
class and passing the target function my_function
as an argument. The start()
method is then called on the thread object to start the new thread. The main thread continues execution and prints “Thread started”. When the new thread finishes executing my_function
, it terminates automatically.
You can pass arguments to the target function by placing them in a tuple and passing the tuple as the args
parameter when creating the thread. For example:
import threading
def my_function(x, y):
print("Starting my_function")
# Your code here
print("Ending my_function")
thread = threading.Thread(target=my_function, args=(1, 2))
thread.start()
print("Thread started")
In this example, my_function
is called with arguments 1 and 2.