How to force a thread to stop

Gerhard Fiedler gelists at gmail.com
Wed Jul 26 23:01:06 EDT 2006


On 2006-07-26 21:38:06, Carl J. Van Arsdall wrote:

>>> Also, threading's condition and event constructs are used a lot 
>>> (i talk about it somewhere in that thing I wrote).  They are easy to use 
>>> and nice and ready for me, with a server wouldn't I have to have things 
>>> poll/wait for messages?
>>
>> How would a thread receive a message, unless it polls some kind of queue or
>> waits for a message from a queue or at a semaphore? You can't just "push" a
>> message into a thread; the thread has to "pick it up", one way or another. 
>   
> Well, I guess I'm thinking of an event driven mechanism, kinda like 
> setting up signal handlers.  I don't necessarily know how it works under 
> the hood, but I don't poll for a signal.  I setup a handler, when the 
> signal comes, if it comes, the handler gets thrown into action.  That's 
> what I'd be interesting in doing with threads.

What you call an event handler is a routine that gets called from a message
queue polling routine. You said a few times that you don't want that. 

The queue polling routine runs in the context of the thread. If any of the
actions in that thread takes too long, it will prevent the queue polling
routine from running, and therefore the event won't get handled. This is
exactly the scenario that you seem to want to avoid. Event handlers are not
anything multitask or multithread, they are simple polling mechanisms with
an event queue. It just seems that they act preemtively, when you can click
on one button and another button becomes disabled :)

There are of course also semaphores. But they also have to either get
polled like GUI events, or the thread just goes to sleep until the
semaphore wakes it up. You need to understand this basic limitation: a
processor can only execute statements. Either it is doing other things,
then it must, by programming, check the queue -- this is polling. Or it can
suspend itself (the thread or process) and tell the OS (or the thread
handling mechanism) to wake it up when a message arrives in a queue or a
semaphore gets active.

You need to look a bit under the hood, so to speak... That's why I said in
the other message that I think it would do you some good to read up a bit
on multitasking OS programming techniques in general. There are not that
many, in principle, but it helps to understand the basics.

Gerhard




More information about the Python-list mailing list