asynchat and threading

Elbert Lev elbertlev at hotmail.com
Wed Nov 24 15:19:10 EST 2004


Rob!

Sure it was suggested you may go with twisted. But with minimal
modifications of asyncore you can add a hook.
There are 2 ways to do this:
1. Use small timeout
2. Use a "control socket"

Timeout:

from asyncore import *

def loop(timeout=30.0, use_poll=0, map=None, after_pool = None):
    if map is None:
        map = socket_map

    if use_poll:
        if hasattr(select, 'poll'):
            poll_fun = poll3
        else:
            poll_fun = poll2
    else:
        poll_fun = poll

    while map:
        poll_fun(timeout, map)
        if (after_pool):
            after_pool(map)

after_pool - is a function called when you exit  poll_fun. You can do
whatever you want in this function.
If you call loop with timeout 0.3 - for all practical reasons your GUI
will react OK. If there are a few sockets (I think 1 in your case),
the overhead will be negligible on any reasonable computer.

The second approach is more effective, but more complex too. You add a
socket (as channel 0) and when something happens (f.e. user presses
enter), you write a byte (or any command you want).  Write into this
control socket has to be made atomic to be thread save.

The reason I do not use twisted for client applications is the size of
distribution file. I do not assume python is installed on client PC.
I use distutils with py2exe option. If I use twisted the size is
10mb+.  With asyncore - 2-3 mb.

Hope this helps.



More information about the Python-list mailing list