Python 简明教程

Python - Creating a Thread

在 Python 中创建线程涉及在程序中启动单独的执行流,从而允许多个操作同时运行。这对于同时执行任务特别有用,例如并行处理各种 I/O 操作。

Creating a thread in Python involves initiating a separate flow of execution within a program, allowing multiple operations to run concurrently. This is particularly useful for performing tasks simultaneously, such as handling various I/O operations in parallel.

Python 提供了多种创建和管理线程的方法。

Python provides multiple ways to create and manage threads.

  1. Creating a thread using the threading module is generally recommended due to its higher-level interface and additional functionalities.

  2. On the other hand, the _thread module offers a simpler, lower-level approach to create and manage threads, which can be useful for straightforward, low-overhead threading tasks.

在本教程中,您将学习使用不同的方法在 Python 中创建线程的基础知识。我们将介绍使用函数创建线程,从 thread 模块扩展 Thread 类,以及使用 _thread 模块创建线程。

In this tutorial, you will learn the basics of creating threads in Python using different approaches. We will cover creating threads using functions, extending the Thread class from the threading module, and utilizing the _thread module.

Creating Threads with Functions

您可以使用 threading 模块中的 Thread 类创建线程。在此方法中,只需将函数传递给 Thread 对象,即可创建一个线程。以下是如何启动新线程的步骤:

You can create threads by using the Thread class from the threading module. In this approach, you can create a thread by simply passing a function to the Thread object. Here are the steps to start a new thread −

  1. Define a function that you want the thread to execute.

  2. Create a Thread object using the Thread class, passing the target function and its arguments.

  3. Call the start method on the Thread object to begin execution.

  4. Optionally, call the join method to wait for the thread to complete before proceeding.

Example

以下示例演示了在 Python 中使用线程进行并发执行。它通过指定 Thread 类中作为目标的用户定义函数,创建并启动多个并发执行不同任务的线程。

The following example demonstrates concurrent execution using threads in Python. It creates and starts multiple threads that execute different tasks concurrently by specifying user-defined functions as targets within the Thread class.

from threading import Thread

def addition_of_numbers(x, y):
   result = x + y
   print('Addition of {} + {} = {}'.format(x, y, result))

def cube_number(i):
   result = i ** 3
   print('Cube of {} = {}'.format(i, result))

def basic_function():
   print("Basic function is running concurrently...")

Thread(target=addition_of_numbers, args=(2, 4)).start()
Thread(target=cube_number, args=(4,)).start()
Thread(target=basic_function).start()

在执行上述程序时,它将产生以下结果:

On executing the above program, it will produces the following result −

Addition of 2 + 4 = 6
Cube of 4 = 64
Basic function is running concurrently...

Creating Threads by Extending the Thread Class

创建线程的另一种方法是扩展 Thread 类。此方法涉及定义一个从 Thread 继承并重写其 init 和 run 方法的新类。以下是如何启动新线程的步骤:

Another approach to creating a thread is by extending the Thread class. This approach involves defining a new class that inherits from Thread and overriding its init and run methods. Here are the steps to start a new thread −

  1. Define a new subclass of the Thread class.

  2. Override the init method to add additional arguments.

  3. Override the run method to implement the thread’s behavior.

Example

此示例演示了如何使用扩展 Python 中 threading.Thread 类的自定义 MyThread 类创建和管理多个线程。

This example demonstrates how to create and manage multiple threads using a custom MyThread class that extends the threading.Thread class in Python.

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print ("Starting " + self.name)
      print_time(self.name, 5, self.counter)
      print ("Exiting " + self.name)

def print_time(threadName, counter, delay):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print ("%s: %s" % (threadName, time.ctime(time.time())))
      counter -= 1

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()
print ("Exiting Main Thread")

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Mon Jun 24 16:38:10 2024
Thread-2: Mon Jun 24 16:38:11 2024
Thread-1: Mon Jun 24 16:38:11 2024
Thread-1: Mon Jun 24 16:38:12 2024
Thread-2: Mon Jun 24 16:38:13 2024
Thread-1: Mon Jun 24 16:38:13 2024
Thread-1: Mon Jun 24 16:38:14 2024
Exiting Thread-1
Thread-2: Mon Jun 24 16:38:15 2024
Thread-2: Mon Jun 24 16:38:17 2024
Thread-2: Mon Jun 24 16:38:19 2024
Exiting Thread-2

Creating Threads using start_new_thread() Function

_thread module 中包含的 start_new_thread() 函数用于在正在运行的程序中创建新线程。此模块提供了低级别的线程处理方法。它更简单,但没有线程模块提供的一些高级功能。

The start_new_thread() function included in the _thread module is used to create a new thread in the running program. This module offers a low-level approach to threading. It is simpler but does not have some of the advanced features provided by the threading module.

以下是 _thread.start_new_thread() 函数的语法:

Here is the syntax of the _thread.start_new_thread() Function

_thread.start_new_thread ( function, args[, kwargs] )

此函数启动一个新线程并返回其标识符。 function 参数指定新线程将执行的函数。此函数所需的任何参数都可以使用 args 和 kwargs 传递。

This function starts a new thread and returns its identifier. The function parameter specifies the function that the new thread will execute. Any arguments required by this function can be passed using args and kwargs.

Example

import _thread
import time
# Define a function for the thread
def thread_task( threadName, delay):
   for count in range(1, 6):
      time.sleep(delay)
      print ("Thread name: {} Count: {}".format ( threadName, count ))

# Create two threads as follows
try:
    _thread.start_new_thread( thread_task, ("Thread-1", 2, ) )
    _thread.start_new_thread( thread_task, ("Thread-2", 4, ) )
except:
   print ("Error: unable to start thread")

while True:
   pass

thread_task("test", 0.3)

它将生成以下 output

It will produce the following output

Thread name: Thread-1 Count: 1
Thread name: Thread-2 Count: 1
Thread name: Thread-1 Count: 2
Thread name: Thread-1 Count: 3
Thread name: Thread-2 Count: 2
Thread name: Thread-1 Count: 4
Thread name: Thread-1 Count: 5
Thread name: Thread-2 Count: 3
Thread name: Thread-2 Count: 4
Thread name: Thread-2 Count: 5
Traceback (most recent call last):
 File "C:\Users\user\example.py", line 17, in <module>
  while True:
KeyboardInterrupt

程序进入无限循环。您必须按下 ctrl-c 才能停止。

The program goes in an infinite loop. You will have to press ctrl-c to stop.