-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
56 lines (44 loc) · 1.27 KB
/
test.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
import asyncio
import threading
from asyncio.locks import Event
class EventWithErr(Event):
def __init__(self, loop):
super().__init__(loop=loop)
def set(self, e=None):
self.e = e
return super().set()
async def fire():
raise BaseException("ERR")
async def fire_and_forget():
async def fire_and_catch_err():
try:
await fire()
except BaseException as e:
stop_event.set(e)
f = asyncio.ensure_future(fire_and_catch_err())
loop = asyncio.new_event_loop()
loop.set_debug(True)
stop_event = EventWithErr(loop)
async def main_loop():
"""非同期スレッドの本体
エラーが起きるまで動かし続ける。"""
print("Start Loop")
await stop_event.wait()
if stop_event.e:
raise stop_event.e
def start_loop():
try:
loop.run_until_complete(main_loop())
except:
print("Catch Thread", loop.is_running())
loop.close()
raise
thread = threading.Thread(target=start_loop, name="Test", daemon=True)
thread.start()
asyncio.run_coroutine_threadsafe(fire_and_forget(), loop)
print("wait...")
from time import sleep
sleep(10)
print(thread.is_alive())
asyncio.run_coroutine_threadsafe(fire_and_forget(), loop)
print("bye")