Curses programming, threads?

Carl Banks imbosol at aerojockey.com
Fri Dec 3 19:44:35 CET 2004


Bartlomiej Rymarski <bart at oceanic.wsisiz.edu.pl> wrote in message news:<copfes$uus$1 at portraits.wsisiz.edu.pl>...
> Hello, 
> 
> I'm writing this little program, and I've came across a function
> that I need to call. Since the execution of the function takes a 
> real long time I want to put a timer, or an animated 'loading' 
> screen (it would be best if it was a progressbar). The questions is
> how to make two commands to run at the same time. 
> 
[snip]
>
> It would be best if I could operate with like this:
> 
> #v+
> def function:
> 	do loader() while
> 		connect_db()
> #v-
> 
> And the loader() function would run in a loop until connect_db() is 
> is finished. Is that possible in python? 

Generally speaking, to do this in C, on Unix, without threads, one
would use the setitimer system call, along with SIGALARM.  (Doubtful
available on all Unices, and there are probably other ways, but I'd
guess this is the most common way to do it.  It is available on Linux;
I've used it before.)  AFAIK, Python does not expose the setitimer
call, so you can't do it that way in Python without writing a C
extension.  (It would be a pretty simple extension to write, though.)

In Python, you could use the signal.alarm() call in much the same way.
 The downside is that you can only update the little animation once
per second.  Something like this could do what you want (untested):

    def alarm_handler(*args):
        if loaded:
            return
        update_animation()
        signal.alarm(1)

    signal.signal(signal.SIGALARM,alarm_handler)
    signal.alarm(1)
    loaded = False
    connect_db()
    loaded = True

But I recommend threads for this.  It's one of the easiest possible
uses of threads.  There's no complex communication involved; locks and
semaphores and stuff aren't required.  Just connect to the database in
a subthread, and have it set a global flag just before it exits. 
Animate in a loop in the main thread, checking the flag every
iteration, and when it's true, you're done.


-- 
CARL BANKS



More information about the Python-list mailing list