counter.py 657 字节
Newer Older
F
feilong 已提交
1
# -*- coding: UTF-8 -*-
F
feilong 已提交
2
# 作者:huanhuilong
F
feilong 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# 标题: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)