1import asyncio
2import time
3import threading
45# このあたりはデバッグ用なので本質にはあまり関係ないです67start = time.perf_counter()8tidc =-19tids ={}1011defgettid():12global tidc
13 i = threading.get_ident()14if i notin tids:15 tidc +=116 tids[i]= tidc
17return tids[i]1819defdbg(m):20 ct = time.perf_counter()- start
21 tid = gettid()22print(f"${tid:03d}:{ct:.3f}: {m}")2324# 同期I/Oを行う関数(asyncioのloop配下で動くように下ごしらえしたもの)2526deftask(name):27defblocking_io():28 dbg(f"task: {name} async i/o starts")29 time.sleep(0.5)30 dbg(f"task: {name} async i/o completed")31return name
3233 loop = asyncio.get_running_loop()34return loop.run_in_executor(None, blocking_io)3536# 非同期I/Oを行う関数3738asyncdefatask(name):39 dbg(f"atask: {name} async i/o starts")40await asyncio.sleep(0.5)41 dbg(f"atask: {name} async i/o starts")42return name
4344# メイン処理4546asyncdefmain():47 dbg("main run blocking i/o simultaneously")48 t1 = task("A")49 t2 = task("B")50 t3 = task("C")51 dbg(f"main task result is {type(t1)}")52 result =await asyncio.gather(t1, t2, t3)53 dbg(f"main completed result={result}")54 dbg("main run non-blocking i/o simultaneously")55 t1 = atask("A")56 t2 = atask("B")57 t3 = atask("C")58 dbg(f"main task result is {type(t1)}")59 result =await asyncio.gather(t1, t2, t3)60 dbg(f"main completed result={result}")616263asyncio.run(main())
sh
1$ python3 t.py
2$000:0.002: main run blocking i/o simultaneously
3$001:0.005: task: A async i/o starts
4$002:0.006: task: B async i/o starts
5$003:0.006: task: C async i/o starts
6$000:0.006: main task result is <class '_asyncio.Future'>
7$002:0.511: task: B async i/o completed
8$003:0.511: task: C async i/o completed
9$001:0.511: task: A async i/o completed
10$000:0.513: main completed result=['A', 'B', 'C']
11$000:0.513: main run non-blocking i/o simultaneously
12$000:0.513: main task result is <class 'coroutine'>
13$000:0.513: atask: A async i/o starts
14$000:0.514: atask: B async i/o starts
15$000:0.514: atask: C async i/o starts
16$000:1.026: atask: A async i/o starts
17$000:1.027: atask: B async i/o starts
18$000:1.027: atask: C async i/o starts
19$000:1.027: main completed result=['A', 'B', 'C']
20#回答者コメント
21#^ここはスレッドidみたいなもの
22# ^ここは経過時間(秒)
23$
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/23 05:20