Use the built-in threading module.
import threading
Quick links:
The core class is threading.Thread.
Define the target function: This is the code that the new thread will run.
def my_thread_task(argument1, argument2):
# Code to be executed in the new thread
print(f"Thread received: {argument1}, {argument2}")
# ... perform task ...
Create a Thread object:
thread = threading.Thread(target=my_thread_task, args=(value1, value2))
target: The function to be executed in the new thread.args: A tuple of positional arguments to pass to the target function. Use a comma after the single item if passing only one argument (e.g., args=(value1,)).kwargs: (Optional) A dictionary of keyword arguments to pass to the target function.Start the thread:
thread.start()
Wait for the thread to complete:
thread.join()
join() method is called terminates.import threading
import time
def worker_function(name):
print(f"Worker thread {name} starting...")
time.sleep(2) # Simulate doing some I/O work
print(f"Worker thread {name} finishing.")
# Create two threads
t1 = threading.Thread(target=worker_function, args=("Alpha",))
t2 = threading.Thread(target=worker_function, args=("Beta",))
# Start the threads
t1.start()
t2.start()
# Wait for both threads to complete
t1.join()
t2.join()
print("All threads finished.")
Threads share memory, which makes data sharing easier but requires careful synchronization (using Locks, Semaphores, etc.) to prevent race conditions.