面试题答案
一键面试锁机制解决资源竞争问题描述
在Python多线程编程中,通过引入锁(Lock
)来解决资源竞争问题。锁是一种同步原语,它只有两种状态:锁定(locked)和未锁定(unlocked)。当一个线程获取到锁(将锁的状态变为锁定),其他线程就无法获取该锁,直到这个线程释放锁(将锁的状态变为未锁定)。这样就保证了在同一时间只有一个线程可以访问共享资源,避免了资源竞争。
Python代码示例
import threading
# 共享资源
counter = 0
# 创建锁对象
lock = threading.Lock()
def increment():
global counter
for _ in range(1000000):
# 获取锁
lock.acquire()
try:
counter += 1
finally:
# 释放锁
lock.release()
threads = []
for _ in range(2):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"最终的计数器值: {counter}")
在上述代码中,定义了一个共享变量 counter
,并使用 Lock
来保护对 counter
的修改操作。在 increment
函数中,每次对 counter
进行修改前先获取锁,修改完成后释放锁。这样即使多个线程同时调用 increment
函数,也不会出现资源竞争导致的错误结果。