-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdistribute_lock_asyncio.py
executable file
·99 lines (76 loc) · 2.41 KB
/
distribute_lock_asyncio.py
1
2
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
import asyncio
import uuid
from tair import TairError
from tair.asyncio import Tair
# change the following configuration for your Tair.
TAIR_HOST = "localhost"
TAIR_PORT = 6379
TAIR_DB = 0
TAIR_USERNAME = None
TAIR_PASSWORD = None
tair = None
async def init():
global tair
tair = Tair(
host=TAIR_HOST,
port=TAIR_PORT,
db=TAIR_DB,
username=TAIR_USERNAME,
password=TAIR_PASSWORD,
)
LOCK_KEY: str = "LOCK_KEY"
class Account:
def __init__(self, balance: int) -> None:
self.balance = balance
# try_lock locks atomically via set with NX flag
# request_id prevents the lock from being deleted by mistake
# expire_time is to prevent the deadlock of business machine downtime
async def try_lock(key: str, request_id: str, expire_time: int) -> bool:
try:
result = await tair.set(key, request_id, ex=expire_time, nx=True)
# if the command was successful, return True
# else return None
return result is not None
except TairError as e:
print(e)
return False
# release_lock atomically releases the lock via the CAD command
# request_id ensures that the released lock is added by itself
async def release_lock(key: str, request_id: str) -> bool:
try:
result = await tair.cad(key, request_id)
# if the key doesn't exist, return -1
# if the request_id doesn't match, return 0
# else return 1
return result == 1
except TairError as e:
print(e)
return False
async def deposit_and_withdraw(account: Account) -> None:
request_id = str(uuid.uuid4())
if await try_lock(LOCK_KEY, request_id, 2):
print(f"balance: {account.balance}")
if account.balance != 10:
raise RuntimeError(
f"balance should not be negative value: {account.balance}"
)
account.balance += 1000
await asyncio.sleep(1)
account.balance -= 1000
await release_lock(LOCK_KEY, request_id)
await asyncio.sleep(1)
async def task_func(account: Account) -> None:
while True:
await deposit_and_withdraw(account)
async def main():
await init()
account = Account(10)
tasks = []
for i in range(10):
task = asyncio.create_task(task_func(account))
tasks.append(task)
for task in tasks:
await task
if __name__ == "__main__":
asyncio.run(main())