并发线程和数据竞争是多线程编程中常见的问题,解决方法有以下几种:
import threading
# 共享数据
shared_data = 0
# 互斥锁
mutex = threading.Lock()
def increment():
global shared_data
for _ in range(100000):
mutex.acquire()
shared_data += 1
mutex.release()
def decrement():
global shared_data
for _ in range(100000):
mutex.acquire()
shared_data -= 1
mutex.release()
# 创建两个线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=decrement)
# 启动线程
thread1.start()
thread2.start()
# 等待线程执行完毕
thread1.join()
thread2.join()
print(shared_data) # 输出 0
import threading
# 共享数据
shared_data = 0
# 条件变量
condition = threading.Condition()
def increment():
global shared_data
for _ in range(100000):
with condition:
while shared_data >= 1:
condition.wait()
shared_data += 1
condition.notify()
def decrement():
global shared_data
for _ in range(100000):
with condition:
while shared_data <= -1:
condition.wait()
shared_data -= 1
condition.notify()
# 创建两个线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=decrement)
# 启动线程
thread1.start()
thread2.start()
# 等待线程执行完毕
thread1.join()
thread2.join()
print(shared_data) # 输出 0
import threading
import concurrent.futures
# 共享数据
shared_data = 0
def increment():
global shared_data
for _ in range(100000):
shared_data += 1
def decrement():
global shared_data
for _ in range(100000):
shared_data -= 1
# 创建线程池
with concurrent.futures.ThreadPoolExecutor() as executor:
# 提交任务
futures = [executor.submit(increment), executor.submit(decrement)]
# 等待任务完成
concurrent.futures.wait(futures)
print(shared_data) # 输出 0
这些解决方法可以有效避免并发线程和数据竞争问题,确保多线程程序的正确性和稳定性。
上一篇:并发线程访问单例模式