実現したいこと
asyncを使った非同期処理をうまく並列に動かしたい
発生している問題・エラーメッセージ
task1とtask2が同時に出力させたいのにtask1しか結果を出力できていない
現状、task1,task2片方をコメントアウトすれば、それぞれは正常に動く状態です。
python-binanceを使っています
該当のソースコード
Python
1from __future__ import annotations 2 3import asyncio 4 5from binance import AsyncClient, DepthCacheManager, BinanceSocketManager, ThreadedDepthCacheManager 6 7 8# main関数 9async def main(symbol): 10 # tradesを取得するタスクとdepthを取得するタスクを起動 11 t = await trades(symbol) 12 task1 = asyncio.create_task(t) 13 # depthを取得するタスクを起動 14 task2 = asyncio.create_task(depth(symbol)) 15 await asyncio.gather(task1, task2) 16 17 18async def trades(symbol): 19 client = await AsyncClient.create() 20 bsm = BinanceSocketManager(client) 21 22 async with bsm.individual_symbol_ticker_futures_socket(symbol) as fs: 23 while True: 24 res = await fs.recv() 25 print(res['data']['c']) 26 27 28async def depth(symbol): 29 dcm = ThreadedDepthCacheManager() 30 # 深さ情報を取得 31 # start is required to initialise its internal loop 32 dcm.start() 33 34 def handle_depth_cache(depth_cache): 35 print(f"symbol {depth_cache.symbol}") 36 print("top 5 bids") 37 print(depth_cache.get_bids()[:5]) 38 print("top 5 asks") 39 print(depth_cache.get_asks()[:5]) 40 print("last update time {}".format(depth_cache.update_time)) 41 42 dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol=symbol) 43 44 dcm.join() 45 46 47if __name__ == "__main__": 48 loop = asyncio.get_event_loop() 49 loop.run_until_complete(main('ETHUSDT'))

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/02/07 10:47
2023/02/07 11:11