在 Python 中创建线程涉及在程序中启动单独的执行流,从而允许多个操作同时运行。这对于同时执行任务特别有用,例如并行处理各种 I/O 操作。
Python 提供了多种创建和管理线程的方法。
- 通常建议使用 threading 模块创建线程,因为它具有更高级别的接口和附加功能。
- 另一方面,_thread 模块提供了一种更简单、更低级别的方法来创建和管理线程,这对于简单的、低开销的线程任务非常有用。
在本教程中,您将学习使用不同方法在 Python 中创建线程的基础知识。我们将介绍如何使用函数创建线程、从 threading 模块扩展 Thread 类以及使用 _thread 模块。
使用 Functions 创建线程
可以使用 threading 模块中的 Thread 类创建线程。在这种方法中,只需将函数传递给 Thread 对象即可创建线程。以下是开始新线程的步骤 -
- 定义您希望线程执行的函数。
- 使用 Thread 类创建一个 Thread 对象,并传递目标函数及其参数。
- 对 Thread 对象调用 start 方法以开始执行。
- (可选)调用 join 方法以等待线程完成,然后再继续。
例
以下示例演示了在 Python 中使用线程的并发执行。它通过在 Thread 类中将用户定义的函数指定为目标,创建并启动多个并发执行不同任务的线程。
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()
在执行上述程序时,它将产生以下结果 -
Cube of 4 = 64
Basic function is running concurrently...
通过扩展 Thread 类创建线程
创建线程的另一种方法是扩展 Thread 类。此方法涉及定义一个从 Thread 继承的新类,并重写其 __init__ 和 run 方法。以下是开始新线程的步骤 -
- 定义 Thread 类的新子类。
- 重写 __init__ 方法以添加其他参数。
- 重写 run 方法以实现线程的行为。
例
此示例演示如何使用扩展线程的自定义 MyThread 类创建和管理多个线程。Thread 类。
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-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
使用 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-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 才能停止。