Python并发编程:锁、竞态条件与全局解释器锁
1. 锁的弊端
1.1 并发程序变为顺序执行
我们来看下面这个 Python 代码示例,它用于比较并发程序和顺序程序的执行速度:
import threading
import random; random.seed(0)
import time
def update(pause_period):
global counter
with count_lock:
current_counter = counter # 读取共享资源
time.sleep(pause_period) # 模拟大量计算
counter = current_counter + 1 # 更新共享资源
pause_periods = [random.randint(0, 1) for i in range(20)]
# 顺序版本
counter = 0
count_lock = threading.Lock()
start = time.perf_counter()
for i in range(20):
update(pause_periods[i])
print('--Sequential version--')
print(f'Final counter: {counter}.')
print(f'Took {time.perf_counter() - start : .2f} seconds.')
# 并发版本
counter = 0
threads = [threading.Thread(target
超级会员免费看
订阅专栏 解锁全文

5320

被折叠的 条评论
为什么被折叠?



