Python并发编程:锁和死锁示例

原创 蔚落 2025-01-14 23:42 64阅读 0赞

在Python中,多线程编程中会涉及到锁(Lock)和死锁(Deadlock)的概念。下面我们将通过具体的示例来理解这两者。

  1. 锁(Lock)
    锁是一种同步原语,用于保护共享资源不被并发访问修改。Python内置的threading.Lock()类就是锁的一种实现。

示例:

  1. import threading
  2. # 创建一个锁
  3. lock = threading.Lock()
  4. def thread_function():
  5. with lock:
  6. print("Thread %s acquired lock" % threading.currentThread().name)
  7. # 这里会阻塞,直到锁被释放
  8. time.sleep(5)
  9. print("Thread %s released lock" % threading.currentThread().name)
  10. # 创建多个线程
  11. threads = []
  12. for i in range(5):
  13. thread = threading.Thread(target=thread_function)
  14. threads.append(thread)
  15. thread.start()
  16. # 等待所有线程结束
  17. for thread in threads:
  18. thread.join()
  1. 死锁(Deadlock)
    死锁是指两个或多个并发进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉,它们都将无法推进下去。

示例:

  1. import threading
  2. # 两个互有依赖的线程
  3. def thread1():
  4. print("Thread 1 waiting for lock from Thread 2")
  5. lock2.acquire()
  6. print("Thread 1 acquired lock from Thread 2")
  7. time.sleep(5)
  8. print("Thread 1 releasing lock to Thread 2")
  9. lock2.release()
  10. def thread2():
  11. print("Thread 2 waiting for lock from Thread 1")
  12. lock1.acquire()
  13. print("Thread 2 acquired lock from Thread 1")
  14. time.sleep(5)
  15. print("Thread 2 releasing lock to Thread 1")
  16. lock1.release()
  17. # 创建两个互有锁的线程
  18. lock1 = threading.Lock()
  19. lock2 = threading.Lock()
  20. threads = [threading.Thread(target=thread1), 'Thread 1'),
  21. [threading.Thread(target=thread2)), 'Thread 2']
  22. for thread in threads:
  23. thread.start()
  24. for thread in threads:
  25. thread.join()

总结:

  • 锁是并发编程中用于保护共享资源的机制。
  • 死锁是指两个或多个线程因争夺资源而无法推进的现象。

在实际应用中,需要谨慎设计并发控制策略,避免产生死锁。

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

发表评论

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

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

相关阅读