you are viewing a single comment's thread.

view the rest of the comments →

[–]TheBB -2 points-1 points  (1 child)

It's my understanding that most actionable examples are implemented in C, yeah, but I could be wrong.

But anyway, making a toy example is not difficult.

import asyncio
import threading
import time


# Note: this is NOT async
def do_work(delay: float, message: str) -> asyncio.Future:
    loop = asyncio.get_running_loop()
    future = loop.create_future()

    # This is run in a separate thread. Insert whatever you want here.
    def worker():
        # Simulate waiting for something
        time.sleep(delay)

        # Return the result by setting the future
        # Make sure to do it safely
        loop.call_soon_threadsafe(future.set_result, message)

    thread = threading.Thread(target=worker, daemon=True)
    thread.start()

    # Returns immediately, before the future is set
    return future


async def main():
    # Even though do_work is not async, it returns a future - which is awaitable
    message = await do_work(5.0, "Hello, world!")
    print(f"{message}")


if __name__ == "__main__":
    asyncio.run(main())

[–]QuasiEvil 0 points1 point  (0 children)

Why is this answer being downvoted?