面试题答案
一键面试关键代码逻辑(以Python多线程为例,使用threading.Lock
)
import threading
shared_dict = {'a': 1, 'b': 2, 'c': 3}
lock = threading.Lock()
def accumulate():
total = 0
with lock:
for value in shared_dict.values():
total += value
print(f"累加结果: {total}")
threads = []
for _ in range(5):
t = threading.Thread(target=accumulate)
threads.append(t)
t.start()
for t in threads:
t.join()
采用的同步机制及原因
- 同步机制:这里采用了
threading.Lock
(互斥锁)。 - 原因:在多线程环境下,当多个线程同时访问和修改共享资源(如
shared_dict
)时,可能会出现竞态条件,导致数据不一致。互斥锁可以保证在同一时刻只有一个线程能够进入临界区(这里是对shared_dict
进行遍历和累加的代码块),其他线程需要等待锁的释放。这样就避免了多个线程同时操作共享字典,从而保证了数据的一致性。
多进程实现(以Python多进程为例,使用multiprocessing.Lock
)
import multiprocessing
shared_dict = {'a': 1, 'b': 2, 'c': 3}
lock = multiprocessing.Lock()
def accumulate():
total = 0
with lock:
for value in shared_dict.values():
total += value
print(f"累加结果: {total}")
if __name__ == '__main__':
processes = []
for _ in range(5):
p = multiprocessing.Process(target=accumulate)
processes.append(p)
p.start()
for p in processes:
p.join()
在多进程中使用multiprocessing.Lock
也是出于同样目的,多进程之间共享资源同样存在竞态条件问题,通过锁来确保同一时间只有一个进程能操作共享字典,保证数据一致性。