SoFunction
Updated on 2025-03-03

Detailed explanation of how to create and end threads using python

Python create thread and end thread

In Python, threads are a lightweight execution unit that allows us to execute multiple tasks simultaneously in a program. Thread creation and ending is one of the core concepts in multithreading programming. In this article, we will learn how to create threads using Python and explore how to end threads gracefully.

Create thread

Creating threads in Python is very simple and can be usedthreadingModule to implement. Here is a simple example:

import threading
import time

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

# Create threadthread = (target=print_numbers)

# Start the thread()

# The main thread waits for the child thread to complete execution()

print("Thread execution is completed!")

In this example, we create a function called print_numbers that prints numbers from 1 to 5. We then create a new thread using the class and specify the objective function to execute. Finally, start the thread by calling the start() method and wait for the thread execution to complete through the join() method.

End thread

Ending threads is usually to allow the program to exit normally without the thread continuing to execute, or to terminate the thread's execution under certain conditions. In Python, threads cannot be terminated directly, but threads can be exited by setting flags or sending signals. Here is a simple example:

import threading
import time

# Global flag bits, control thread executionis_running = True

def count_numbers():
    i = 1
    while is_running:
        print(i)
        i += 1
        (1)

# Create threadthread = (target=count_numbers)

# Start the thread()

# The main thread waits for a period of time and modifys the flag bit to end the thread(5)
is_running = False

print("Waiting for thread execution to complete...")
()

print("Thread execution is completed!")

In this example, we create a name calledcount_numbersfunction, which continuously prints numbers and passes a global variableis_runningControls the execution of threads. In the main thread, we waited for 5 seconds and thenis_runningSet toFalse, so that the thread exits on its own.

Safe end thread

In addition to the way of setting flag bits, sometimes we may need to end threads more safely and reliably. Threads in Python do not provide direct methods to force terminate threads, but you can use some tricks to end threads safely, such as usingThreadThe object'sEvent

Here is a useEventExample to end the thread:

import threading
import time

# Create Event objectstop_event = ()

def count_numbers():
    i = 1
    while not stop_event.is_set():
        print(i)
        i += 1
        (1)

# Create threadthread = (target=count_numbers)

# Start the thread()

# The main thread waits for a period of time and sets Event to end the thread(5)
stop_event.set()

print("Waiting for thread execution to complete...")
()

print("Thread execution is completed!")

In this example, we created aEventObjectstop_event, the thread checks whether the event is set in each loop. In the main thread, we waited for 5 seconds and set itstop_event, thus ending the execution of the thread.

Exception handling

In the thread, exception handling is also an important issue. If an exception occurs in the thread and is not processed, the entire thread may terminate unexpectedly. Therefore, use it in the threadtry-exceptStatement to catch exceptions and perform appropriate processing.

Here is a simple example:

import threading
import time

def task():
    try:
        # Here is the task executed by the thread        print("The mission begins...")
        (3)
        raise Exception("Authorized throw")
    except Exception as e:
        print(f"Catched exception:{e}")

# Create threadthread = (target=task)

# Start the thread()

# The main thread waits for the thread execution to complete()

print("Thread execution is completed!")

In this example, the task in the thread throws an exception, but because we aretaskUsed in the functiontry-exceptstatement, so the exception is caught and printed, and the thread does not terminate unexpectedly.

Manage threads using thread pool

In actual development, if threads are frequently created and destroyed, it may lead to performance degradation. To manage threads more efficiently, thread pools can be used to reuse thread objects. Python provides modules, and the ThreadPoolExecutor class can help us manage thread pools easily.

Here is an example of using thread pools:

from  import ThreadPoolExecutor
import time

def task(n):
    print(f"Task {n} start...")
    (2)
    print(f"Task {n} Finish!")

# Create a thread poolwith ThreadPoolExecutor(max_workers=3) as executor:
    # Submit tasks to thread pool execution    for i in range(1, 6):
        (task, i)

print("All tasks are executed!")

In this example, we useThreadPoolExecutorA thread pool with a maximum number of worker threads is created. Then, we submit 5 tasks to the thread pool for execution. The thread pool will automatically manage thread creation and destruction and task scheduling.

Subclasses used

In addition to using it directlyIn addition to the class, we can also inheritCreate a custom thread class. Doing so will make the code better organized and can be rewrited in subclassesrun()Methods to define the logic of thread execution.

Here is a simple example:

import threading
import time

class MyThread():
    def __init__(self, name):
        super().__init__()
         = name

    def run(self):
        print(f"{} The thread starts executing...")
        (3)
        print(f"{} Thread execution is completed!")

# Create a thread instance and startthread1 = MyThread("Thread 1")
thread2 = MyThread("Thread 2")

()
()

# Wait for thread execution to complete()
()

print("All threads are executed!")

In this example, we define aMyThreadClass, inherited from, and rewrittenrun()Methods to define the logic of thread execution. Then we created twoMyThreadinstance and started both threads.

Thread synchronization and sharing resources

In multi-threaded programming, multiple threads often encounter situations where shared resources are accessed at the same time. In order to avoid the problems of race conditions and data inconsistencies, thread synchronization mechanisms are needed to protect shared resources.

Use Lock

Locks are one of the most common thread synchronization mechanisms, in PythonClasses can be used to create lock objects. Before accessing shared resources, threads can callacquire()Method acquires the lock and call it after the access is completed.release()Method to release the lock.

Here is an example of using locks to protect shared resources:

import threading

shared_resource = 0
lock = ()

def update_shared_resource():
    global shared_resource
    for _ in range(100000):
        ()
        shared_resource += 1
        ()

# Create multiple threads to update shared resourcesthreads = []
for _ in range(5):
    t = (target=update_shared_resource)
    (t)
    ()

# Wait for all threads to completefor t in threads:
    ()

print("The value of the shared resource is:", shared_resource)

In this example, we create a shared variable called shared_resource and then create a lock object lock using . In the update_shared_resource function, we use locks to protect access to shared_resource, thus avoiding the problem of multiple threads modifying shared resources at the same time.

Use condition variables (Condition)

Conditional variables are another common thread synchronization mechanism, in PythonClasses can be used to create conditional variable objects. Condition variables are usually used in conjunction with locks to notify waiting threads when a specific condition is met.

Here is an example of using conditional variables to implement the producer-consumer pattern:

import threading
import time

MAX_ITEMS = 5
items = []
condition = ()

def producer():
    for i in range(10):
        (1)
        with condition:
            if len(items) >= MAX_ITEMS:
                print("The warehouse is full, the producer is waiting...")
                ()
            print("Producer produces a commodity")
            (i)
            ()

def consumer():
    for i in range(10):
        (1.5)
        with condition:
            while not items:
                print("The warehouse is empty, consumers are waiting...")
                ()
            item = (0)
            print(f"Consumers consumed the goods {item}")
            ()

# Create producer and consumer threads and startproducer_thread = (target=producer)
consumer_thread = (target=consumer)

producer_thread.start()
consumer_thread.start()

# Wait for thread execution to completeproducer_thread.join()
consumer_thread.join()

print("All commodities have been produced and consumed!")

In this example, we use the conditional variableconditionTo realize the producer-consumer model. The producer thread waits when the warehouse is full, the consumer thread waits when the warehouse is empty, and passes after production or consumption is completed.notify()Method notifies the waiting thread.

Use queues to achieve inter-thread communication

In addition to using synchronization mechanisms such as locks and condition variables, queues can also be used to achieve secure communication between threads. In PythonClasses provide thread-safe queue implementations that can safely pass data between multiple threads.

Here is an example of using queues to implement the producer-consumer pattern:

import threading
import queue
import time

MAX_ITEMS = 5
queue = (MAX_ITEMS)

def producer():
    for i in range(10):
        (1)
        try:
            (i, block=True, timeout=1)
            print("Producer produces a commodity")
        except :
            print("The warehouse is full, the producer is waiting...")

def consumer():
    for i in range(10):
        (1.5)
        try:
            item = (block=True, timeout=1)
            print(f"Consumers consumed the goods {item}")
        except :
            print("The warehouse is empty, consumers are waiting...")

# Create producer and consumer threads and startproducer_thread = (target=producer)
consumer_thread = (target=consumer)

producer_thread.start()
consumer_thread.start()

# Wait for thread execution to completeproducer_thread.join()
consumer_thread.join()

print("All commodities have been produced and consumed!")

In this example, we use classes to implement the producer-consumer pattern. The producer thread adds products to the queue through the put() method, and the consumer thread uses the get() method to retrieve products from the queue. When the queue is full, the producer thread will wait; when the queue is empty, the consumer thread will wait.

The advantage of using queues to achieve inter-thread communication is that it provides a simple and secure way to pass data, avoiding explicit locks and conditional variables.

Timed end thread

Sometimes, we hope that the thread will execute within a certain time or exit from timeout. This function can be achieved in Python using timers. The timer can trigger an event after a specified time, and we can use this feature to control the execution time of the thread.

Here is an example of ending a thread using a timer:

import threading
import time

def task():
    print("The thread starts executing...")
    (3)  # Simulate thread execution time    print("Thread execution is completed!")

# Create threadthread = (target=task)

# Start the thread()

# Timer, set the thread end flag after 3 secondsdef set_thread_finished():
    print("Timer triggers, sets the thread end flag...")
     = True

timer = (3, set_thread_finished)
()

# The main thread waits for the thread execution to complete()

print("Thread execution is completed!")

In this example, we create a timertimer, triggered after 3 secondsset_thread_finishedFunction, this function sets the end flag of the thread. The thread checks the end flag when executing, and exits early if the flag is set. This implements the function of ending the thread after a specified time.

Implement thread waiting using

In addition to timers, we can also useTo implement thread waiting and timeout exit.EventIt is a mechanism for inter-thread communication, which can be used to set signals, wait for signals and other operations.

Here is a useEventExamples of implementing thread waiting:

import threading
import time

# Create Event objectevent = ()

def task():
    print("The thread starts executing...")
    (3)  # Wait for the event to trigger, timeout is 3 seconds    if event.is_set():
        print("The event is triggered, and the thread execution is completed!")
    else:
        print("Timeout exit, thread execution is not completed!")

# Create threadthread = (target=task)

# Start the thread()

# Set events after waiting for a while(2)
print("Set events after waiting for 2 seconds...")
()

# The main thread waits for the thread execution to complete()

print("Thread execution is completed!")

In this example, the thread waits for the event to be triggered during execution. If the event is set within 3 seconds, the thread execution is completed; otherwise, the thread exits after the timeout. This implements the function of ending the thread within a specified time.

Summarize

In this article, we explore multiple ways to create threads, end threads, and thread management in Python. We start with the basics of creating threads, introduce how to create threads using the threading module, and show how to end threads gracefully. Next, we discuss in-depth the issues of thread synchronization and shared resources, and introduce methods to use mechanisms such as locks, condition variables and queues to protect shared resources and realize inter-thread communication. We then explore how to use timers and events to achieve thread timing end and timeout exit, so as to more flexible control of thread execution time.

Overall, this article provides a comprehensive introduction to key concepts and techniques in multithreaded programming and provides rich code examples to help readers better understand and apply these techniques. By rationally using thread management and synchronization mechanisms, we can write efficient and reliable multi-threaded programs to better utilize computing resources and improve program performance and maintainability. Hope this article will be helpful to readers in Python multithreading programming.

The above is a detailed explanation of how to use python to create and end threads. For more information about python creating and ending threads, please follow my other related articles!