Python - 创建线程



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

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

  • 通常建议使用threading模块创建和管理线程,因为它具有更高级别的接口和附加功能。

  • 另一方面,_thread模块提供了一种更简单、更低级的创建和管理线程的方法,这对于简单的、低开销的线程任务很有用。

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

使用函数创建线程

您可以使用threading模块中的Thread类来创建线程。在这种方法中,您可以通过简单地将函数传递给 Thread 对象来创建线程。以下是启动新线程的步骤:

  • 定义线程要执行的函数。
  • 使用 Thread 类创建一个 Thread 对象,传递目标函数及其参数。
  • 调用 Thread 对象上的 start 方法以开始执行。
  • 可选地,调用 join 方法以等待线程完成,然后再继续执行。

示例

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

Open Compiler
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()

执行上述程序后,将产生以下结果:

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

通过扩展 Thread 类创建线程

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

  • 定义 Thread 类的新的子类。
  • 覆盖 __init__ 方法以添加附加参数。
  • 覆盖 run 方法以实现线程的行为。

示例

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

Open Compiler
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")

执行上述代码后,将产生以下结果:

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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

使用 start_new_thread() 函数创建线程

_thread 模块中包含的start_new_thread()函数用于在正在运行的程序中创建一个新线程。此模块提供了一种低级线程方法。它更简单,但不具备 threading 模块提供的一些高级功能。

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

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

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

示例

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)

它将产生以下输出

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停止。

广告