Debian Codegraph @

docs/source/reference-core/from-thread-example.py

raw
1 import trio
2
3
4 def thread_fn(receive_from_trio, send_to_trio):
5 while True:
6 # Since we're in a thread, we can't call methods on Trio
7 # objects directly -- so we use trio.from_thread to call them.
8 try:
9 request = trio.from_thread.run(receive_from_trio.receive)
10 except trio.EndOfChannel:
11 trio.from_thread.run(send_to_trio.aclose)
12 return
13 else:
14 response = request + 1
15 trio.from_thread.run(send_to_trio.send, response)
16
17
18 async def main():
19 send_to_thread, receive_from_trio = trio.open_memory_channel(0)
20 send_to_trio, receive_from_thread = trio.open_memory_channel(0)
21
22 async with trio.open_nursery() as nursery:
23 # In a background thread, run:
24 # thread_fn(receive_from_trio, send_to_trio)
25 nursery.start_soon(
26 trio.to_thread.run_sync, thread_fn, receive_from_trio, send_to_trio
27 )
28
29 # prints "1"
30 await send_to_thread.send(0)
31 print(await receive_from_thread.receive())
32
33 # prints "2"
34 await send_to_thread.send(1)
35 print(await receive_from_thread.receive())
36
37 # When we close the channel, it signals the thread to exit.
38 await send_to_thread.aclose()
39
40 # When we exit the nursery, it waits for the background thread to
41 # exit.
42
43
44 trio.run(main)