在并发/多线程编程中,可能会出现多个线程同时执行相同代码的情况,从而可能生成相同的输出。这种情况被称为竞态条件(Race Condition)。
要解决竞态条件,可以采用以下方法之一:
import threading
# 共享资源
shared_variable = 0
# 创建锁
lock = threading.Lock()
def increment():
global shared_variable
lock.acquire() # 获取锁
try:
shared_variable += 1
finally:
lock.release() # 释放锁
# 创建多个线程并启动
threads = []
for _ in range(10):
thread = threading.Thread(target=increment)
thread.start()
threads.append(thread)
# 等待所有线程结束
for thread in threads:
thread.join()
# 输出结果
print(shared_variable) # 输出:10
import threading
import queue
# 创建线程安全队列
q = queue.Queue()
def producer():
for i in range(10):
q.put(i) # 向队列中放入数据
def consumer():
while not q.empty():
item = q.get() # 从队列中取出数据
print(item)
# 创建生产者线程和消费者线程并启动
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)
producer_thread.start()
consumer_thread.start()
# 等待生产者线程和消费者线程结束
producer_thread.join()
consumer_thread.join()
通过加锁或使用线程安全的数据结构,可以避免竞态条件,确保多线程并发执行时生成正确的输出结果。