-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_local.py
53 lines (39 loc) · 1.03 KB
/
_local.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
import random
import threading
import contextvars, asyncio
def thread_run_next():
for i in range(100):
local.num = local.num + 1
def thread_run():
local.num = random.randint(1,10)
for i in range(100):
local.num = local.num + 1
thread_run_next()
print(local.num)
def threading_run():
global local
local = threading.local()
t1 = threading.Thread(target=thread_run)
t2 = threading.Thread(target=thread_run)
t1.start()
t2.start()
async def two(i):
# lock = contextvars.ContextVar("lock")
for i in range(100):
lock.set(lock.get() + 1)
async def one(i):
# lock = contextvars.ContextVar("lock")
print(lock.get())
lock.set(i)
await two(i)
for i in range(100):
lock.set(lock.get() + 1)
print(lock.get())
async def async_run():
global lock
lock = contextvars.ContextVar("lock",default="")
tasks = [one(i) for i in range(5)]
await asyncio.gather(*tasks)
if __name__ == '__main__':
#threading_run()
asyncio.run(async_run())