Python – Starting a Thread

Introduction

Starting a thread in Python allows you to run multiple tasks concurrently, making your programs more efficient and responsive. The threading module provides a simple and effective way to create and manage threads. This guide covers how to start a thread, including passing arguments to threads, creating daemon threads, and handling multiple threads.

Starting a Thread

Basic Thread Creation and Starting

To start a thread, you need to create an instance of the Thread class and then call its start() method. The thread will then execute the target function passed to it.

Example

import threading

def print_numbers():
    for i in range(1, 6):
        print(i)

# Create a thread
thread = threading.Thread(target=print_numbers)

# Start the thread
thread.start()

# Wait for the thread to complete
thread.join()

print("Thread execution completed.")

Output

1
2
3
4
5
Thread execution completed.

Passing Arguments to a Thread

You can pass arguments to the target function using the args parameter when creating the thread.

Example

import threading

def print_numbers(n):
    for i in range(1, n + 1):
        print(i)

# Create a thread
thread = threading.Thread(target=print_numbers, args=(5,))

# Start the thread
thread.start()

# Wait for the thread to complete
thread.join()

print("Thread execution completed.")

Output

1
2
3
4
5
Thread execution completed.

Creating and Starting a Daemon Thread

Daemon threads are background threads that automatically terminate when all non-daemon threads have finished executing. You can make a thread a daemon by setting the daemon attribute to True before starting the thread.

Example

import threading
import time

def print_numbers():
    for i in range(1, 6):
        print(i)
        time.sleep(1)

# Create a daemon thread
thread = threading.Thread(target=print_numbers)
thread.daemon = True

# Start the thread
thread.start()

# Main program will not wait for the daemon thread to complete
print("Main program execution completed.")

Output

1
2
Main program execution completed.
3
4
5

Creating and Starting Multiple Threads

You can create and start multiple threads to perform concurrent tasks. This can significantly improve the performance of I/O-bound and high-level structured network code.

Example

import threading

def print_numbers(thread_id, n):
    for i in range(1, n + 1):
        print(f"Thread {thread_id}: {i}")

# Create multiple threads
threads = []
for i in range(3):
    thread = threading.Thread(target=print_numbers, args=(i + 1, 5))
    threads.append(thread)
    thread.start()

# Wait for all threads to complete
for thread in threads:
    thread.join()

print("All threads have finished execution.")

Output

Thread 1: 1
Thread 2: 1
Thread 3: 1
Thread 1: 2
Thread 2: 2
Thread 3: 2
Thread 1: 3
Thread 2: 3
Thread 3: 3
Thread 1: 4
Thread 2: 4
Thread 3: 4
Thread 1: 5
Thread 2: 5
Thread 3: 5
All threads have finished execution.

Thread State and Lifecycle

When a thread is started, it goes through different states: New, Runnable, Running, Waiting/Blocked, and Terminated.

  • New: The thread is created but not yet started.
  • Runnable: The thread is ready to run and waiting for CPU time.
  • Running: The thread is currently being executed by the CPU.
  • Waiting/Blocked: The thread is waiting for a resource or another thread to perform an action.
  • Terminated: The thread has finished its execution.

Conclusion

Starting a thread in Python is straightforward using the threading module. You can create threads by passing a function or subclassing the Thread class, pass arguments to threads, create daemon threads, and manage multiple threads concurrently. Understanding how to start and manage threads is essential for building efficient and responsive multithreaded applications in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top