47 lines
1.1 KiB
Python
47 lines
1.1 KiB
Python
import t, c
|
|
from stdint import *
|
|
from w32.win32base import *
|
|
from w32.win32sync import (
|
|
InitializeSRWLock,
|
|
AcquireSRWLockExclusive, ReleaseSRWLockExclusive,
|
|
AcquireSRWLockShared, ReleaseSRWLockShared
|
|
)
|
|
|
|
|
|
@t.Object
|
|
class RWLock:
|
|
"""基于 SRWLock 的读写锁,支持多读单写,不支持递归。
|
|
|
|
用法:
|
|
rwlock: RWLock = RWLock()
|
|
rwlock.acquire_read()
|
|
# ... 读取共享数据
|
|
rwlock.release_read()
|
|
rwlock.acquire_write()
|
|
# ... 修改共享数据
|
|
rwlock.release_write()
|
|
"""
|
|
lock: VOIDPTR
|
|
|
|
def __init__(self):
|
|
InitializeSRWLock(c.Addr(self.lock))
|
|
|
|
def acquire_read(self):
|
|
AcquireSRWLockShared(c.Addr(self.lock))
|
|
|
|
def release_read(self):
|
|
ReleaseSRWLockShared(c.Addr(self.lock))
|
|
|
|
def acquire_write(self):
|
|
AcquireSRWLockExclusive(c.Addr(self.lock))
|
|
|
|
def release_write(self):
|
|
ReleaseSRWLockExclusive(c.Addr(self.lock))
|
|
|
|
def __enter__(self) -> 'RWLock' | t.CPtr:
|
|
self.acquire_write()
|
|
return self
|
|
|
|
def __exit__(self):
|
|
self.release_write()
|