From ef6a635663451972906b0847b26d60e69567fc5b Mon Sep 17 00:00:00 2001 From: Cam <yulinfeng000@gmail.com> Date: Wed, 9 Feb 2022 09:22:06 +0800 Subject: [PATCH] update BWS_Package counter --- .gitignore | 3 ++- blive/core.py | 40 +++++++++++++++++++++++++--------------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index 63385e2..1a03696 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ **/__pycache__ dist build -blive.egg-info \ No newline at end of file +blive.egg-info +test.py \ No newline at end of file diff --git a/blive/core.py b/blive/core.py index 6794c3b..d0c4ebf 100644 --- a/blive/core.py +++ b/blive/core.py @@ -1,3 +1,4 @@ +import asyncio from collections import namedtuple from multiprocessing import RawValue, Lock import json @@ -94,28 +95,37 @@ class Operation(enum.IntEnum): class Counter(object): - # 线程安全计数器 - def __init__(self, init_value) -> None: - self.current = RawValue("i", init_value) - self.lock = Lock() + def __init__(self, init_value=0) -> None: + self.current = init_value def increment(self): - with self.lock: - self.current.value += 1 + self.current += 1 def value(self): - with self.lock: - return self.current.value + return self.current def increment_get(self): - with self.lock: - self.current.value += 1 - return self.current.value + self.current += 1 + return self.current - def get_increment(self): - with self.lock: - yield self.current.value - self.current.value += 1 + +class AsyncCounter: + def __init__(self) -> None: + self.current = 0 + self.lock = asyncio.Lock() + + async def increment(self): + async with self.lock: + self.current += 1 + + async def increment_get(self): + async with self.lock: + self.current += 1 + return self.current + + async def value(self): + async with self.lock: + return self.current PackageHeader = namedtuple(