Skip to content

In trio.to_thread.run, give a better error message if passed a sync function #1244

@kantrol

Description

@kantrol

I needed to decouple sender and receiver and initialized the channel with max_buffer_size>0. Lost elements are accepted when buffer is full, but sendchannel.send_nowait throws

TypeError: object NoneType can't be used in 'await' expression

I had expected that the channel could be filled up to max_buffer_size.
For demonstration I made minor changes to the threaded channel example:

import trio

def thread_fn(receive_from_trio, send_to_trio):
    while True:
        # Since we're in a thread, we can't call methods on Trio
        # objects directly -- so we use trio.from_thread to call them.
        try:
            request = trio.from_thread.run(receive_from_trio.receive)
            response = request + 1
            trio.from_thread.run(send_to_trio.send_nowait, response)
        except trio.WouldBlock:
            print('would block')
        except trio.EndOfChannel:
            trio.from_thread.run(send_to_trio.aclose)
            return

async def main():
    send_to_thread, receive_from_trio = trio.open_memory_channel(1)
    send_to_trio, receive_from_thread = trio.open_memory_channel(1)

    async with trio.open_nursery() as nursery:
        # In a background thread, run:
        #   thread_fn(portal, receive_from_trio, send_to_trio)
        nursery.start_soon(
            trio.to_thread.run_sync, thread_fn, receive_from_trio, send_to_trio
        )

        # prints "1"
        await send_to_thread.send(0)
        
        # simulate a slow starting receiver
        await trio.sleep(2)
        print(await receive_from_thread.receive())       

        # prints "2"
        await send_to_thread.send(1)
        print(await receive_from_thread.receive())

        # When we close the channel, it signals the thread to exit.
        await send_to_thread.aclose()

        # When we exit the nursery, it waits for the background thread to
        # exit.


trio.run(main)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions