-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
38 lines (27 loc) · 900 Bytes
/
example.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
import aioguest, asyncio, trio
# This is the example from Trio's guest mode docs, with the loops swapped.
# A tiny asyncio program
async def aio_main():
for _ in range(5):
print("Hello from asyncio!")
await asyncio.sleep(1)
return "trio done!"
# The code to run it as a guest inside Trio
async def trio_main():
trio_token = trio.lowlevel.current_trio_token()
done_evt = trio.Event()
aio_outcome = None
def done_callback(outcome):
nonlocal aio_outcome
aio_outcome = outcome
done_evt.set()
aioguest.start_guest_run(
aio_main(),
run_sync_soon_threadsafe=trio_token.run_sync_soon,
done_callback=done_callback,
)
# Wait for the guest run to finish
await done_evt.wait()
# Pass through the return value or exception from the guest run
return aio_outcome.unwrap()
trio.run(trio_main)