0
0
PythonHow-ToBeginner · 3 min read

How to Create Thread in Python: Simple Guide with Examples

To create a thread in Python, use the threading.Thread class by passing a target function to run in the new thread. Start the thread with the start() method to run the function concurrently with the main program.
📐

Syntax

Use the threading.Thread class to create a thread. You provide a target function that the thread will run. Call start() on the thread object to begin execution.

  • threading.Thread(target=function_name): Creates a thread to run function_name.
  • start(): Starts the thread and runs the target function concurrently.
  • join(): Waits for the thread to finish before continuing.
python
import threading

def worker():
    print('Thread is running')

thread = threading.Thread(target=worker)
thread.start()
thread.join()
Output
Thread is running
💻

Example

This example shows how to create and start a thread that runs a simple function printing messages. The main program waits for the thread to finish using join().

python
import threading
import time

def print_numbers():
    for i in range(1, 6):
        print(f'Number {i}')
        time.sleep(0.5)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
print('Thread finished')
Output
Number 1 Number 2 Number 3 Number 4 Number 5 Thread finished
⚠️

Common Pitfalls

Common mistakes when creating threads include:

  • Calling the target function directly instead of passing it to Thread. This runs the function immediately in the main thread.
  • Forgetting to call start(), so the thread never runs.
  • Not using join() when you need to wait for the thread to finish, causing unpredictable program flow.
python
import threading

def task():
    print('Task running')

# Wrong: calls task immediately, no new thread
thread = threading.Thread(target=task)  # Incorrect

# Correct way
thread = threading.Thread(target=task)  # Pass function without ()
thread.start()
thread.join()
Output
Task running
📊

Quick Reference

ActionCode Example
Create threadthread = threading.Thread(target=your_function)
Start threadthread.start()
Wait for threadthread.join()
Define functiondef your_function():\n # code to run in thread

Key Takeaways

Use threading.Thread with a target function to create a thread.
Always call start() to run the thread concurrently.
Use join() to wait for the thread to finish if needed.
Pass the function name without parentheses to target, not the result of calling it.
Threads run alongside the main program, enabling multitasking.