Python并发编程:threading模块详解

Python的threading模块提供了一个高级的、基于线程的并发接口。线程是操作系统能够进行运算调度的最小单位。它被包含在每个进程中,是进程中的实际运作单位。Python的threading模块让你能够创建多个线程,从而在同一时间内执行多个操作。

threading模块的主要特点

  • 线程管理:可以轻松创建和管理线程。
  • 同步机制:提供锁(Locks)、事件(Events)、条件变量(Condition)等同步原语。
  • 线程池:通过ThreadPoolExecutor类实现线程池,方便执行并发任务。

常用threading函数及其参数

Thread()

创建一个线程对象。

  • group: 线程组(通常为None)。
  • target: 线程启动时调用的函数。
  • name: 线程的名称(默认情况下是Thread-N)。
  • args: 传递给target函数的参数。
  • kwargs: 以关键字形式传递给target函数的参数。

Lock()

创建一个锁对象。

  • locked: 初始锁定状态(默认为False)。

Event()

创建一个事件对象。

  • event: 初始状态(默认为False)。

Condition()

创建一个条件变量对象。

  • lock: 关联的锁对象。

Semaphore()

创建一个信号量对象。

  • value: 信号量的初始值。

BoundedSemaphore()

创建一个有界信号量对象。

  • value: 信号量的初始值。

Thread.start()

启动线程。

  • 无参数。

Thread.join()

等待线程终止。

  • timeout: 等待时间(可选)。

Lock.acquire()

获取锁。

  • blocking: 是否阻塞(默认为True)。
  • timeout: 超时时间(默认为None)。

Lock.release()

释放锁。

示例

以下是一个使用threading模块创建线程的示例:
假设我们有一个简单的银行账户类,我们需要确保在多线程环境下对账户余额的访问是线程安全的。

import threading
import time
import random

# 银行账户类
class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance
        self.lock = threading.Lock()

    def deposit(self, amount):
        with self.lock:
            new_balance = self.balance + amount
            time.sleep(random.random())  # 模拟处理时间
            self.balance = new_balance
            print(f"Deposited {
      
      amount}. New balance is {
      
      self.balance}.")

    def withdraw(self, amount):
        with self.lock:
            if self.balance >= amount:
                new_balance = self.balance - amount
                time.sleep(random.random())  # 模拟处理时间
                self.balance = new_balance
                print(f"Withdrew {
      
      amount}. New balance is {
      
      self.balance}.")
            else:
                print("Insufficient funds.")

# 创建银行账户
account = BankAccount(1000)

# 定义存款和取款的操作
def deposit_to_account(amount):
    account.deposit(amount)

def withdraw_from_account(amount):
    account.withdraw(amount)

# 创建线程列表
threads = []

# 创建并启动存款线程
for i in range(5):
    thread = threading.Thread(target=deposit_to_account, args=(200,))
    threads.append(thread)
    thread.start()

# 创建并启动取款线程
for i in range(5):
    thread = threading.Thread(target=withdraw_from_account, args=(100,))
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("All transactions are complete.")

在这个示例中,我们定义了一个BankAccount类,它有一个deposit方法和一个withdraw方法,用于存款和取款。这两个方法都使用了threading.Lock来确保在多线程环境下对账户余额的修改是安全的。

我们创建了两个操作:deposit_to_account和withdraw_from_account,它们分别调用BankAccount的deposit和withdraw方法。然后,我们创建了多个线程来执行存款和取款操作。每个线程都启动后,我们使用join方法等待所有线程完成。

这个示例展示了如何在多线程环境中使用锁来同步对共享资源的访问,确保了操作的原子性和线程安全。

猜你喜欢

转载自blog.csdn.net/qq_57143062/article/details/141938839