[Tutor] What exactly does "await" do? (David)

Alan Gauld alan.gauld at yahoo.co.uk
Tue Feb 14 19:35:36 EST 2023


On 14/02/2023 04:40, Alphonsus Okoye wrote:

>> A coroutine can be recognised by having 'async def' in its
>> definition statement, as opposed to just 'def' for the
>> definition of an ordinary function or method.

> main purpose of a coroutine?

You've been given the technical answer to that. It's basically
a routine that can be run as part of a set of concurrently
executing functions. However, it's not just a case of using the
async syntax. You also need to take care not to leave global
resources in unstable states. For example files written to
but not flushed etc. Otherwidse the other coroutines may try
to access them and bad things start happening. Similarly it is easy to
create deadlock scenarios where two routines compete for the
sameresource, each locking the other out.

As a result writing concurrent code is a non trivial exercise
requiring considerable thought and care.

> More specifically, if I wished to write a program that read from a long
> text file "spam.txt", and while the process begins to waste time, do other
> stuff like call function doOtherStuff(), what would the code look like?

In general I'd suggest threading for that scenario rather
than async. Simpler and lighter weight. Writing a web server
or other transaction based processor is a more common
scenario for async. Something where the parallel tasks
are more varied and of non determinate nature. Reading from
a file may take a while but it is fairly predictable.
Of course, if the file were a batch file containing instructions
for a variey of transaction types, some of them in turn
requiring network, database or file access, then async might
well be the appropriate engine for processing the file contents.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list