So ,
Here is what Ive coded up, works perfectly. Emulates a very simple - albeit hack - message driven model.
from Queue import Queue from threading import Thread from enum import Enum # State of this worker thread class State(Enum): Stopped = 0x01 Idle = 0x02 Busy = 0x04 # Threding Queue. All messages for work are posted into this. Queue = Queue(maxsize=0) # Message blocks placed on queue class MessageBlock(object): def __init__(self, type, callback): self._type = type self._callback = callback def doAction(self): self._callback() class Worker: _state = State.Stopped def state(self): return self._state def setBusy(self): print("setBusy()") self._state = State.Busy def setIdle(self): print("setIdle()") self._state = State.Idle def stop(self): print("Stop()") self._state = State.Stopped def start(self): print("Start()") self.setIdle() print("start: setting up worker") worker = Thread(target=self.doMainLoop, args=(Queue,)) worker.setDaemon(True) worker.start() print("start: join queue") Queue.join() #print("start: stopping") #self.stop() def doMainLoop(self, messageQueue): print("doMainLoop() state={}".format(self.state())) print while self.state() != State.Stopped: print("doMainLoop: starting loop") self.setIdle() message = messageQueue.get() self.setBusy() print("doMainLoop: invoking doAction of message block") message.doAction() messageQueue.task_done() print("doMainLoop: action done") print("doMainLoop() ends") def callbackFunc(): print ("callback function called")
msg = Worker.MessageBlock("proc",Worker.callbackFunc) worker = Worker.Worker() worker.start() ... <setup msg> Worker.Queue.put(msg) ... <setup msg> Worker.Queue.put(msg) .. worker.stop()
Simple and effective. Probably need coding ettiqute and style, and not what members would end up with, but works for me.
All I need to do throug my code is setup a series of simple message blocks consisting of a name and a callback functions, and push these into the Queue; the callback functions can (I guess - not tried yet!!) setup their own message blocks to prevent blocking. The worker thread will non-block wait for messages to be pushed into the queue and invoke the callback specified within the message. I will of course need to add message data and arguments, a trivial matter, but I wanted to share this with the community given the pain I had to endure to get here. I always like to help
Tags to help future searches:
blocking
messaging
threading
multitasking
spinner
worker