40 lines
963 B
Python
40 lines
963 B
Python
import t, c
|
|
from stdint import *
|
|
from w32.win32base import *
|
|
from w32.win32sync import CRITICAL_SECTION, InitializeCriticalSection, EnterCriticalSection, LeaveCriticalSection, DeleteCriticalSection, TryEnterCriticalSection
|
|
|
|
|
|
@t.Object
|
|
class Lock:
|
|
"""基于 CRITICAL_SECTION 的互斥锁,支持递归加锁。
|
|
|
|
用法:
|
|
lock: Lock = Lock()
|
|
with lock:
|
|
# 临界区
|
|
pass
|
|
"""
|
|
cs: CRITICAL_SECTION
|
|
|
|
def __init__(self):
|
|
InitializeCriticalSection(c.Addr(self.cs))
|
|
|
|
def acquire(self):
|
|
EnterCriticalSection(c.Addr(self.cs))
|
|
|
|
def release(self):
|
|
LeaveCriticalSection(c.Addr(self.cs))
|
|
|
|
def try_acquire(self) -> BOOL:
|
|
return TryEnterCriticalSection(c.Addr(self.cs))
|
|
|
|
def __enter__(self) -> 'Lock' | t.CPtr:
|
|
self.acquire()
|
|
return self
|
|
|
|
def __exit__(self):
|
|
self.release()
|
|
|
|
def delete(self):
|
|
DeleteCriticalSection(c.Addr(self.cs))
|