在多线程编程中,如何避免‘竞态条件’?请给出具体的Python代码示例。

在多线程编程中,避免竞态条件(Race Condition)的关键是通过线程同步机制确保共享资源的原子性操作。以下是几种常见的方法及其Python代码示例:

1. 使用锁(Lock)

锁是最基本的同步机制,通过加锁的方式确保同一时间只有一个线程可以访问临界区。

import threading

# 共享资源
counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        lock.acquire()  # 获取锁
        try:
            counter += 1
        finally:
            lock.release()  # 释放锁

# 创建多个线程
threads = []
for _ in range(10):
    thread = threading.Thread(target=increment)
    threads.append(thread)
    thread.start()

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

print("Final counter value:", counter)  # 预期输出: 1000000

2. 使用RLock(可重入锁)

RLock允许同一个线程多次获取锁,避免死锁问题。

lock = threading.RLock()

def nested_increment():
    global counter
    for _ in range(100000):
        lock.acquire()
        lock.acquire()  # 同一线程可以重复获取锁
        try:
            counter += 1
        finally:
            lock.release()
            lock.release()

# 线程创建与启动逻辑同Lock示例

3. 使用信号量(Semaphore)

信号量可以限制同时访问共享资源的线程数量。

semaphore = threading.Semaphore(3)  # 最多允许3个线程同时访问

def semaphore_example():
    global counter
    semaphore.acquire()
    try:
        counter += 1
    finally:
        semaphore.release()

# 线程创建与启动逻辑同Lock示例

4. 使用条件变量(Condition)

条件变量用于线程间的协调,例如等待某个条件成立后再执行。

condition = threading.Condition()
def wait_condition():
    with condition:
        while counter < 100000:  # 等待条件满足
            condition.wait()
        print("条件满足,继续执行")

# 唤醒等待的线程
def notify_condition():
    with condition:
        counter = 100000
        condition.notify_all()

5. 使用线程安全的数据结构

Python的queue模块提供了线程安全的队列实现。

import queue

q = queue.Queue()

def producer():
    for i in range(100):
        q.put(i)

def consumer():
    while True:
        item = q.get()
        print(f"处理: {item}")
        q.task_done()

总结

竞态条件的核心在于共享资源的同步访问。通过锁、信号量、条件变量等机制,可以确保线程安全。此外,避免全局变量、使用线程安全的数据结构(如queue)也是推荐的做法。

示例中展示了多种同步机制,实际开发中应根据需求选择合适的方式。例如,简单的计数器可以使用锁,而复杂的线程协调可能需要条件变量。