Fork自 CSDN 技术社区 / skill_tree_python
体验新版 GitCode,发现更多精彩内容 >>
# -*- coding: UTF-8 -*-
# 作者:huanhuilong
# 标题:Python 计数器(1) # 描述:非线程安全计数器 from concurrent.futures import ThreadPoolExecutor import time class Counter: def __init__(self) -> None: self.count = 0 def step(self): count = self.count count += 1 time.sleep(0.1) self.count = count print(f'count: {self.count}') if __name__ == '__main__': counter = Counter() for i in range(0, 5): counter.step() assert counter.count == 5 with ThreadPoolExecutor(max_workers=5) as exe: for i in range(0, 5): exe.submit(counter.step)