3

I started learning about asynchronous code, and I have read a lot, but I just can't seem to find very simple examples to try it by myself and understand it better.

I want to write a simple Python (preferably 3.5) program that does the following:

1) Call the dummy async function dummy() that just waits for a few seconds and returns something
2) Continue doing stuff until dummy() returns something
3) Retrieve the return value from dummy() and put in a variable
4) Proceed on doing stuff

How can I do this?

EDIT:
Sorry if this wasn't clear, but I know how to do this using threading. I'm aiming for doing this using the async-await statements and the asyncio module.

1
  • 1
    If you really want to write it yourself, not someone from SO community, you can start reading python documentation on asyncio Commented Oct 22, 2016 at 20:44

2 Answers 2

3

To try to answer your question I've modified one of the example from the asyncio docs to include more of what you are asking for. https://docs.python.org/3/library/asyncio-task.html

import asyncio

result2 = 0

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    result2 = x*y
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

async def dosomethingelse():
    print("I've got a lovely bunch of coconuts")

loop = asyncio.get_event_loop()
tasks = [print_sum(1, 2),
   dosomethingelse(),
   compute(2, 4)
   ]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
print(result2)

If you run the above you should see that dosomethingelse runs, while compute is waiting.

I found asynchronous programming really hard to wrap my mind around. But I think that asyncio is actually much more straightforward than threading or multiprocessing because everything runs in the same memory space and (with simple coroutines like this) the program flow is completely sequential. The first task runs until it hits an await, then the next task gets a chance, and so on. I highly recommend reading through the module documentation, which is quite good and trying to write some examples to explore each topic. Start with coroutines, then chaining, and then callbacks.

EDIT: I'll leave this here as I think it's a good simple example. Comment if you disagree. Note that the yield from syntax is because I was using a slightly older version of python 3 at the time.

I don't remember what tutorial I was reading but here is one of the first asyncio tests I wrote.

import asyncio

@asyncio.coroutine
def my_coroutine(task_name, seconds_to_sleep=3):
    print("{0} sleeping for: {1} seconds".format(task_name, seconds_to_sleep))
    yield from asyncio.sleep(seconds_to_sleep)
    print("{0} is finished".format(task_name))

loop = asyncio.get_event_loop()
tasks = [my_coroutine("task1", 4),
        my_coroutine("task2", 2),
        my_coroutine("task3", 10)]

loop.run_until_complete(asyncio.wait(tasks))
loop.close()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but:how do I keep doing other stuff while the
Thanks but how do I keep doing other stuff while my_coroutine instances are running? And how do I get the return value when using run_until_complete?
@user3134477 Every time a coroutine reaches a yield statement the event loop gives execution time to another coroutine. So your <b>other</b> stuff just goes into another coroutine.
@user3134477 one of the great things about coroutines is that they share memory space. That means you can use a global object to store the result.
1

to stick to your question (because there are other ways to achieve what you want), a simple answer would be as follows:

import threading
import time


results = []

def dummy():
    time.sleep(2)
    results.append("This function result!")
    return

t = threading.Thread(target=dummy)
t.start()

while t.isAlive():
    print('Something')

print(results)  # ['This function result!']

4 Comments

That is probably the simplest way to get that functionality, but I believe the OP wanted a solution using async
@zvone I can't see how you believe that, because he said "but I just can't seem to find very simple examples to try it by myself and understand it better.", from this, I understand that he just wants a simple working example that does what he explained in his question.
That is my conclusion, based on usage of word async. But the question is not clear. If there was some example of an attempt, it would be easier to understand.
I agree with you that with an example we can understand what OP is trying to achieve, but for me "asynchronous application" does not mean asyncio.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.