Pausing and Unpausing Threads

Aaron J. M. ajmacd at ns.sympatico.ca
Sat Aug 11 21:46:16 EDT 2007


Hello,

This is a question about how to pause and unpause threads (as the
title suggests).

I've created an extension of threading.Thread which I'll call Server.
Server has a collection of Controlers.  A Controler has a method
turn(), which lets it do various interesting things.  While the
Server is running, it loops through each of its Controlers and calls
their turn() method.

One of these Controlers is a subclass called DirectedControler.
What a DirectedControler is meant to do is wait until it is given an
Action object it can invoke.  Actions are basically an implementation
of the Command pattern.  Actions are also invalid in certain
circumstances; they return False when executed if they didn't do
anything.  Therefore, when a DirectedControler is given a turn, it
waits while:
    - It has no Action
    - The last Action it was given didn't do anything

Actions are sent to the DirectedControler by a Client that exists in
the main thread.

What I'm trying to figure out is how to make the DirectedControler
pause while it is waiting for a valid Action.  So far I just put it
into a loop like this:

def turn(self):
    while self.__action is None or not self.__action.execute():
        self.__action = None # Throw away invalid actions
        pass

    self.__action = None # Action was valid.  Clear the way for the
                         # next turn's Action.

Where the Action is set like this (by the Client):

def setAction(self, action):
    if self.__action is None:
        self.__action = action

I'm worried that this loop may wast some CPU cycles, and wonder if
there's a better way through thread synchronization using such things
as Events or Conditions.

Thank you,

Aaron J. M.




More information about the Python-list mailing list