在 Python 中,多线程允许您在单个进程中同时运行多个线程,这也称为基于线程的并行性。这意味着程序可以同时执行多个任务,从而提高其效率和响应能力。
Python 中的多线程处理对于多个 I/O 绑定操作特别有用,而不是对于需要大量计算的任务。
通常,计算机程序从头到尾按顺序执行指令。而 Multithreading 将主任务划分为多个子任务并以重叠的方式执行它们。
与进程的比较
操作系统能够同时处理多个进程。它为每个进程分配一个单独的内存空间,以便一个进程无法访问或写入其他进程中的任何内容。
另一方面,线程可以被视为单个程序中的轻量级子进程,它共享分配给它的内存空间,从而促进更轻松的通信和数据共享。因为它们是轻量级的,不需要太多的内存开销;它们比流程便宜。
进程始终从单个线程 (主线程) 开始。如果需要,可以启动一个新线程并将 sub task 委派给它。现在,这两个线程以重叠的方式工作。当分配给辅助线程的任务结束时,它与主线程合并。
线程具有开始、执行序列和结束。它有一个指令指针,用于跟踪它当前在其上下文中的运行位置。
- 它可以被抢占 (中断)
- 当其他线程正在运行时,它可以暂时处于暂停状态(也称为休眠)——这称为 yielding。
Python 中的线程处理模块
Python 的标准库提供了两个用于管理线程的主要模块:_thread 和 threading。
_thread 模块
_thread 模块,也称为低级线程模块,自版本 2 以来一直是 Python 标准库的一部分。它为线程管理提供了一个基本的 API,支持在共享的全局数据空间中并发执行线程。该模块包括用于同步目的的简单锁(互斥锁)。
threading 模块
Python 2.4 中引入的 threading 模块基于 _thread 构建,以提供更高级别和更全面的线程 API。它提供了用于管理线程的强大工具,从而可以更轻松地在 Python 应用程序中使用线程。
threading 模块的主要特点
threading 模块公开了 thread 模块的所有方法,并提供了一些额外的方法 -
- threading.activeCount() − 返回处于活动状态的线程对象数。
- threading.currentThread() − 返回调用方的线程控件中的线程对象数。
- threading.enumerate() − 返回当前处于活动状态的所有线程对象的列表。
除了方法之外,threading 模块还具有实现 threading 的 Thread 类。Thread 类提供的方法如下 -
- 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] )
此方法调用立即返回,新线程开始执行具有给定参数的指定函数。当函数返回时,线程终止。
例
此示例演示如何使用 _thread 模块创建和运行线程。每个线程使用不同的参数运行 print_name 函数。time.sleep(0.5) 调用可确保主程序在退出之前等待线程完成执行。
import _thread
import time
def print_name(name, *arg):
print(name, *arg)
name="qikepu..."
_thread.start_new_thread(print_name, (name, 1))
_thread.start_new_thread(print_name, (name, 1, 2))
time.sleep(0.5)
执行上述代码时,它会产生以下结果 -
qikepu... 1 2
虽然对于低级线程非常有效,但 _thread 模块相比 threading 模块是有限的,threading 模块提供了更多的功能和更高级别的线程管理。
使用 Threading 模块启动新线程
threading 模块提供了 Thread 类,用于创建和管理线程。
以下是使用 threading 模块启动新线程的几个步骤 -
- 创建您希望线程执行的函数。
- 然后,通过传递目标函数及其参数,使用 Thread 类创建一个 Thread 对象。
- 对 Thread 对象调用 start 方法以开始执行。
- (可选)调用 join 方法以等待线程完成,然后再继续。
例
下面的示例演示如何使用 threading 模块创建和启动线程。它运行一个函数 print_name 打印名称以及一些参数。此示例创建两个线程,使用 start() 方法启动它们,并使用 join 方法等待它们完成。
import threading
import time
def print_name(name, *args):
print(name, *args)
name = "qikepu..."
# 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")
执行上述代码时,它会产生以下结果 -
qikepu... 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)
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
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 = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
执行上述代码时,它会产生以下结果 -
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)
process_data(self.name, self.q)
print ("Exiting " + 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))
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
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
执行上述代码时,它会产生以下结果 -
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