在并发编程中,任务之间的数据共享可能导致竞争条件。如何在使用线程池时避免这种情况?请给出具体的代码实现。

在并发编程中,避免竞争条件的核心是确保对共享数据的访问是同步的。以下是几种在使用线程池时避免竞争条件的方法,并附上具体的代码实现。

1. 使用 threading.Lock

threading.Lock 是一种简单的同步机制,可以确保同一时间只有一个线程能够访问共享资源。

import threading
from concurrent.futures import ThreadPoolExecutor

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

def increment():
    global counter
    with lock:
        counter += 1

# 使用线程池
with ThreadPoolExecutor(max_workers=5) as executor:
    for _ in range(1000):
        executor.submit(increment)

print(f"Counter: {counter}")

在这个例子中,lock 确保了 increment 函数的操作是原子的,从而避免了竞争条件。

2. 使用 threading.RLock(可重入锁)

RLock 允许同一个线程多次获取锁,适用于嵌套调用的情况。

import threading
from concurrent.futures import ThreadPoolExecutor

counter = 0
rlock = threading.RLock()

def increment():
    global counter
    with rlock:
        counter += 1

with ThreadPoolExecutor(max_workers=5) as executor:
    for _ in range(1000):
        executor.submit(increment)

print(f"Counter: {counter}")

3. 使用 queue.Queue

线程安全的队列可以用于在不同线程之间传递数据,避免直接共享数据。

import queue
from concurrent.futures import ThreadPoolExecutor

# 共享队列
q = queue.Queue()

def worker():
    while True:
        try:
            item = q.get(block=False)
            print(f"Processing: {item}")
            q.task_done()
        except queue.Empty:
            break

# 填充队列
for i in range(100):
    q.put(i)

with ThreadPoolExecutor(max_workers=5) as executor:
    for _ in range(5):
        executor.submit(worker)

q.join()
print("All tasks completed")

4. 使用 threading.Semaphore

信号量用于控制对共享资源的访问数量。

import threading
from concurrent.futures import ThreadPoolExecutor

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

def limited_resource_task():
    with semaphore:
        print(f"Thread {threading.current_thread().name} accessing resource")

with ThreadPoolExecutor(max_workers=5) as executor:
    for _ in range(10):
        executor.submit(limited_resource_task)

5. 使用 threading.Event

Event 用于线程间通信,可以用于协调多个线程的操作。

import threading
from concurrent.futures import ThreadPoolExecutor

event = threading.Event()

def task():
    print("Waiting for event to trigger")
    event.wait()
    print("Event triggered")

with ThreadPoolExecutor(max_workers=5) as executor:
    futures = [executor.submit(task) for _ in range(5)]
    import time
    time.sleep(2)
    event.set()

总结

避免竞争条件的关键是同步对共享资源的访问。Lock 和 RLock 适用于简单的互斥场景,Queue 提供了一种更高级别的线程安全数据传递方式,Semaphore 可以限制并发访问数量,Event 则用于线程间协调。根据具体场景选择合适的同步机制,以确保线程安全。