Are there any examples of wxPython threading (possibly with MySQLdb)
and/or sending custom events from seperate threads?
Here is what you need:
1) Create a Queue.Queue() and pass it to the worker thread's contructor
2) Create message class of your own design to tell the worker thread what
to do.
3) Create a response class of your own design that carries the results
to a request
4) Add an event handler and class for the gui thread:
import wx.lib.newevent
MyResponseEvent, EVT_MYRESPONSE = wx.lib.newevent.NewEvent()
In the appropriate window where you want to hanble the responses:
EVT_MYRESPONSE(self, OnMyResponse)
Your method:
def OnMyResponse(self, evt):
... evt will be instance of MyResponseEvent ...
evt.msg will be the original message you send
evt.response will be the result
5) To plumb it all in:
From your gui thread, to send a request:
msg=Message(window=self) # window should be the one containing event handler
queue.put(msg)
In your worker thread, do this as the run method:
while True:
msg=queue.get()
do processing work, put into response variable
evt=MyResponseEvent(msg=msg, response=response)
wx.PostEvent(msg.window, evt)
6) To make it production quality (optional
Name the classes better (eg no 'My'
I recommend putting the processing work in a try/except and if any exception
happens, save sys.exc_info() and supply it to MyResponseEvent. The gui thread
can then look at the exception information and display an error, ignore it,
log it or whatever
You can also make this scale to more threads by simply creating more of them
but sharing the same queue. They will automatically pick off work as it
becomes available.
To shutdown, define a special message (or more likely a command within the message)
that causes the thread to exit. If any of the threads do a lot of work (based on
wall time) between looking in the queue, you may want to create a "global" variable
somewhere they check that flags if a shutdown is requested.
Roger