lock_counter.py 842 字节
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 32 33 34 35 36
# 标题:Python 计数器(2)
# 描述:线程安全计数器

from concurrent.futures import ThreadPoolExecutor
import threading
import time


class LockCounter:
    def __init__(self) -> None:
        self.count = 0
        self.lock = threading.Lock()

    def step(self):
        with self.lock:
            count = self.count
            count += 1
            time.sleep(0.1)
            self.count = count
        print(f'lock_counter: {self.count}')

    def size(self):
        count = 0
        with self.lock:
            count = self.count
        return count


if __name__ == '__main__':
    lock_counter = LockCounter()
    with ThreadPoolExecutor(max_workers=5) as exe:
        for i in range(0, 5):
            exe.submit(lock_counter.step)
    assert lock_counter.count == 5