osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Benefits of asyncio


Chris Angelico <rosuav at gmail.com>:

> I don't see how Marko's assertion that event-driven asynchronous
> programming is a breath of fresh air compared with multithreading. The
> only way multithreading can possibly be more complicated is that
> preemption can occur anywhere - and that's exactly one of the big
> flaws in async work, if you don't do your job properly.

Say you have a thread blocking on socket.accept(). Another thread
receives the management command to shut the server down. How do you tell
the socket.accept() thread to abort and exit?

The classic hack is close the socket, which causes the blocking thread
to raise an exception.

The blocking thread might be also stuck in socket.recv(). Closing the
socket from the outside is dangerous now because of race conditions. So
you will have to carefully use add locking to block an unwanted closing
of the connection.

But what do you do if the blocking thread is stuck in the middle of a
black box API that doesn't expose a file you could close?

So you hope all blocking APIs have a timeout parameter. You then replace
all blocking calls with polling loops. You make the timeout value long
enough not to burden the CPU too much and short enough not to annoy the
human operator too much.

Well, ok,

   os.kill(os.getpid(), signal.SIGKILL)

is always an option.


Marko