Python并发编程:锁和死锁示例
在Python中,多线程编程中会涉及到锁(Lock)和死锁(Deadlock)的概念。下面我们将通过具体的示例来理解这两者。
- 锁(Lock)
锁是一种同步原语,用于保护共享资源不被并发访问修改。Python内置的threading.Lock()
类就是锁的一种实现。
示例:
import threading
# 创建一个锁
lock = threading.Lock()
def thread_function():
with lock:
print("Thread %s acquired lock" % threading.currentThread().name)
# 这里会阻塞,直到锁被释放
time.sleep(5)
print("Thread %s released lock" % threading.currentThread().name)
# 创建多个线程
threads = []
for i in range(5):
thread = threading.Thread(target=thread_function)
threads.append(thread)
thread.start()
# 等待所有线程结束
for thread in threads:
thread.join()
- 死锁(Deadlock)
死锁是指两个或多个并发进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉,它们都将无法推进下去。
示例:
import threading
# 两个互有依赖的线程
def thread1():
print("Thread 1 waiting for lock from Thread 2")
lock2.acquire()
print("Thread 1 acquired lock from Thread 2")
time.sleep(5)
print("Thread 1 releasing lock to Thread 2")
lock2.release()
def thread2():
print("Thread 2 waiting for lock from Thread 1")
lock1.acquire()
print("Thread 2 acquired lock from Thread 1")
time.sleep(5)
print("Thread 2 releasing lock to Thread 1")
lock1.release()
# 创建两个互有锁的线程
lock1 = threading.Lock()
lock2 = threading.Lock()
threads = [threading.Thread(target=thread1), 'Thread 1'),
[threading.Thread(target=thread2)), 'Thread 2']
for thread in threads:
thread.start()
for thread in threads:
thread.join()
总结:
- 锁是并发编程中用于保护共享资源的机制。
- 死锁是指两个或多个线程因争夺资源而无法推进的现象。
在实际应用中,需要谨慎设计并发控制策略,避免产生死锁。
还没有评论,来说两句吧...