You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This addressses issue #810 by implementing `trio.from_thread.run` and
`trio.from_thread.run_sync` and deprecating `BlockingTrioPortal`.
Support re-entering the same `Trio.run()` loop by stashing the current
trio token in Thread Local Storage right before `run_sync_in_thread`
spawns a worker thread. When `trio.from_thread.run_sync` or
`trio.from_thread.run` are called in this thread, they can access the
token and use it to re-enter the `Trio.run()` loop.
This commit deprecates `BlockingTrioPortal`. For the majority of
use cases, using the thread local Trio Token should be sufficient. If
for any reason, another special Trio Token needs to be used, it can be
passed as a kwarg to `from_thread.run` and `from_thread.run_sync`.
Here is a snippet from how the new API works:
```python3
import trio
def thread_fn():
start = trio.from_thread.run_sync(trio.current_time)
print("In Trio-land, the time is now:", start)
trio.from_thread.run(trio.sleep, 1)
end = trio.from_thread.run_sync(trio.current_time)
print("And now it's:", end)
async def main():
await trio.run_sync_in_thread(thread_fn)
trio.run(main)
```
Here is how the same code works in "old" Trio:
```python3
import trio
def thread_fn(token):
portal = trio.BlockingTrioPortal(token)
start = portal.run_sync(trio.current_time)
print("In Trio-land, the time is now:", start)
portal.run(trio.sleep, 1)
end = portal.run_sync(trio.current_time)
print("And now it's:", end)
async def main():
token = trio.hazmat.current_trio_token()
await trio.run_sync_in_thread(thread_fn, token)
trio.run(main)
```
0 commit comments