Python - 多线程
在 Python 中,多线程允许在单个进程内并发运行多个线程,这也被称为基于线程的并行性。这意味着程序可以同时执行多个任务,从而提高其效率和响应性。
Python 中的多线程特别适用于多个 I/O 密集型操作,而不是需要大量计算的任务。
通常,计算机程序会顺序执行指令,从开始到结束。而多线程则将主任务分解为多个子任务,并以重叠的方式执行它们。
与进程的比较
操作系统能够并发处理多个进程。它为每个进程分配独立的内存空间,因此一个进程无法访问或写入其他进程的空间。
另一方面,线程可以被视为单个程序中的轻量级子进程,它共享分配给它的内存空间,从而便于通信和数据共享。由于线程轻量且不需要太多内存开销,因此比进程更便宜。
一个进程总是从单个线程(主线程)开始。根据需要,可以启动新线程并将子任务委托给它。现在这两个线程以重叠的方式工作。当分配给辅助线程的任务完成后,它会与主线程合并。
线程有一个开始、执行序列和结束。它有一个指令指针,用于跟踪其上下文中当前运行的位置。
它可以被抢占(中断)
它可以暂时挂起(也称为睡眠),而其他线程在运行——这称为让步。
Python 中的线程处理模块
Python 的标准库提供了两个主要模块来管理线程:_thread 和 threading。
The _thread 模块
_thread 模块,也称为低级线程模块,自 Python 2 版本起就是标准库的一部分。它提供基本的线程管理 API,支持在共享全局数据空间内并发执行线程。该模块包含简单的锁(mutexes)用于同步目的。
The threading 模块
threading 模块于 Python 2.4 引入,它基于 _thread 提供了更高层次、更全面的线程 API。它提供了强大的工具来管理线程,使在 Python 应用程序中使用线程变得更容易。
threading 模块的关键特性
threading 模块暴露了 thread 模块的所有方法,并提供了一些额外的方法——
- threading.activeCount() 返回活动的 thread 对象数量。
- threading.currentThread() 返回调用者线程控制中的 thread 对象数量。
- threading.enumerate() 返回当前活动的 thread 对象列表。
除了这些方法外,threading 模块还有 Thread class 来实现线程。Thread class 提供的方法如下——
- run() run() 方法是线程的入口点。
- start() start() 方法通过调用 run 方法来启动线程。
- join([time]) join() 等待线程终止。
- isAlive() isAlive() 方法检查线程是否仍在执行。
- getName() getName() 方法返回线程的名称。
- setName() setName() 方法设置线程的名称。
启动新线程
在 Python 中创建并启动新线程,可以使用低级的 _thread 模块或更高级的 threading 模块。通常推荐使用 threading 模块,因为它提供了更多功能且使用更方便。下面展示了两种方法。
使用 _thread 模块启动新线程
_thread 模块的 start_new_thread() 方法提供了一种创建并启动新线程的基本方式。该方法在 Linux 和 Windows 上都提供了一种快速高效创建新线程的方式。以下是该方法的语法 −
thread.start_new_thread(function, args[, kwargs] )
该方法调用会立即返回,新线程将开始使用给定的参数执行指定的 function。当 function 返回时,线程终止。
示例
此示例演示了如何使用 _thread 模块创建并运行线程。每个线程使用不同的参数运行 print_name 函数。time.sleep(0.5) 调用确保主程序在退出前等待线程完成执行。
import _thread import time def print_name(name, *arg): print(name, *arg) name="..." _thread.start_new_thread(print_name, (name, 1)) _thread.start_new_thread(print_name, (name, 1, 2)) time.sleep(0.5)
执行上述代码时,会产生以下结果 −
... 1 ... 1 2
虽然它对于低级线程操作非常有效,但与提供更多功能和更高级线程管理的 threading 模块相比,_thread 模块功能有限。
使用 Threading 模块启动新线程
threading 模块提供了 Thread 类,用于创建和管理线程。
使用 threading 模块启动新线程的几个步骤如下 −
- 创建一个线程需要执行的 function。
- 然后使用 Thread 类创建 Thread 对象,并传递目标 function 及其参数。
- 在 Thread 对象上调用 start 方法开始执行。
- 可选地,调用 join 方法等待线程完成后再继续。
示例
以下示例演示了如何使用 threading 模块创建并启动线程。它运行一个 print_name 函数,该函数会打印一个名称以及一些参数。此示例创建两个线程,使用 start() 方法启动它们,并使用 join 方法等待它们完成。
import threading
import time
def print_name(name, *args):
print(name, *args)
name = "..."
# Create and start threads
thread1 = threading.Thread(target=print_name, args=(name, 1))
thread2 = threading.Thread(target=print_name, args=(name, 1, 2))
thread1.start()
thread2.start()
# Wait for threads to complete
thread1.join()
thread2.join()
print("Threads are finished...exiting")
执行上述代码时,会产生以下结果 −
... 1 ... 1 2 Threads are finished...exiting
线程同步
Python 提供的 threading 模块包含一个易于实现的锁机制,可以让你同步线程。通过调用 Lock() 方法来创建一个新的锁,该方法会返回新的锁对象。
新锁对象的 acquire(blocking) 方法用于强制线程同步运行。可选的 blocking 参数让你控制线程是否等待获取锁。
如果将 blocking 设置为 0,则如果无法获取锁,线程会立即返回 0 值;如果成功获取锁,则返回 1 值。如果将 blocking 设置为 1,则线程会阻塞并等待锁被释放。
新锁对象的 release() 方法用于在不再需要锁时释放它。
示例
import threading
import time
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)
# 获取锁以同步线程
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 释放锁以让下一个线程运行
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 启动新线程
thread1.start()
thread2.start()
# 将线程添加到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print ("Exiting Main Thread")
执行上述代码时,会产生以下结果 −
Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread
多线程优先级队列
Queue 模块允许您创建一个新的队列对象,该对象可以容纳指定数量的项目。有以下方法来控制 Queue −
get() − get() 从队列中移除并返回一个项目。
put() − put() 将项目添加到队列中。
qsize() − qsize() 返回当前队列中的项目数量。
empty() − empty() 如果队列为空则返回 True;否则返回 False。
full() − full() 如果队列已满则返回 True;否则返回 False。
示例
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("Starting " + self.name) # 启动 + self.name
process_data(self.name, self.q)
print ("Exiting " + self.name) # 退出 + self.name
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data)) # %s 处理 %s
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# 创建新线程
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# 填充队列
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# 等待队列清空
while not workQueue.empty():
pass
# 通知线程退出
exitFlag = 1
# 等待所有线程完成
for t in threads:
t.join()
print ("Exiting Main Thread") # 退出主线程
执行上述代码时,会产生以下结果 −
Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-1 processing One Thread-2 processing Two Thread-3 processing Three Thread-1 processing Four Thread-2 processing Five Exiting Thread-3 Exiting Thread-1 Exiting Thread-2 Exiting Main Thread