Python并发编程:锁竞争和死锁问题示例

原创 小灰灰 2025-02-11 14:33 53阅读 0赞

在Python中,多线程可能会遇到锁竞争(Race Conditions)和死锁等问题。这里我们将通过两个简单的示例来解释这些问题。

1. 锁竞争示例

假设我们有两个线程A和B,它们共享一个计数器counter,且对它进行加1操作。

  1. import threading
  2. # 共享资源
  3. counter = 0
  4. lock = threading.Lock()
  5. def thread_a():
  6. global counter, lock
  7. with lock:
  8. counter += 1
  9. print(f"A incremented counter: {counter}")
  10. def thread_b():
  11. global counter, lock
  12. with lock:
  13. counter += 2
  14. print(f"B incremented counter: {counter}")
  15. # 创建线程
  16. thread_a = threading.Thread(target=thread_a))
  17. thread_b = threading.Thread(target=thread_b))
  18. # 启动线程
  19. thread_a.start()
  20. thread_b.start()
  21. # 等待所有线程完成
  22. thread_a.join()
  23. thread_b.join()

在这个示例中,线程A和B共享同一个计数器,并且它们都试图对计数器进行加1操作。由于counter是线程共享的资源,所以两个线程可能会同时执行对counter的加1操作。

2. 死锁问题示例

死锁是指在多进程通信(IPC)中,两个或更多的进程在执行过程中因争夺资源而造成的一种僵局状态。

下面是一个简单的Python多线程死锁例子:

  1. import threading
  2. # 线程1需要线程2的锁A
  3. lock_a = threading.Lock()
  4. # 线程2需要线程1的锁B
  5. lock_b = threading.Lock()
  6. def thread1():
  7. global lock_a, lock_b
  8. with lock_a:
  9. print("Thread 1 locked A")
  10. # 假设这里有一个长时间的等待操作
  11. time.sleep(5)
  12. with lock_b:
  13. print("Thread 1 unlocked B and locked A again")
  14. def thread2():
  15. global lock_a, lock_b
  16. with lock_b:
  17. print("Thread 2 locked B")
  18. with lock_a:
  19. print("Thread 2 unlocked A and locked B again")
  20. # 创建线程
  21. thread1 = threading.Thread(target=thread1))
  22. thread2 = threading.Thread(target=thread2))
  23. # 启动线程
  24. thread1.start()
  25. thread2.start()
  26. # 等待所有线程完成
  27. thread1.join()
  28. thread2.join()

在这个例子中,线程1和线程2都试图获取对方的锁(lock_alock_b),从而形成了一个死锁。在实际情况中,要避免这种死锁问题,需要遵循适当的并发控制策略。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,53人围观)

还没有评论,来说两句吧...

相关阅读