wxPython and threads
josiah.carlson at sbcglobal.net
Thu Jul 19 09:54:31 CEST 2007
> I'm writing a search engine in Python with wxPython as the GUI. I have
> the actual searching preformed on a different thread from Gui thread.
> It sends it's results through a Queue to the results ListCtrl which
> adds a new item. This works fine or small searches, but when the
> results number in the hundreds, the GUI is frozen for the duration of
> the search. I suspect that so many search results are coming in that
> the GUI thread is too busy updating lists to respond to events. I've
> tried buffer the results so there's 20 results before they're sent to
> the GUI thread and buffer them so the results are sent every .1
> seconds. Nothing helps. Any advice would be great.
Sending results one at a time to the GUI is going to be slow for any
reasonably fast search engine (I've got a pure Python engine that does
50k results/second without breaking a sweat). Don't do that. Instead,
have your search thread create a list, which it fills with items for
some amount of time, *then* sends it off to the GUI thread (creating a
new list that it then fills, etc.). While you *could* use a Queue, it
is overkill for what you want to do (queues are really only useful when
there is actual contention for a resource and you want to block when a
resource is not available). Create a deque, and use append() and popleft().
To signal to the GUI thread that there are results available in your
deque, you can use wx.CallAfter(), which will be run in the GUI thread
when the event comes up. Alternatively, you can use a combination of
wx.PostEvent() and wx.lib.newevent (see:
http://wiki.wxpython.org/CustomEventClasses ) to pass the results, or
even just signal that 'more results are available in the deque'. I
would suggest merely signaling that more results are in the deque (using
wx.PostEvent() or wx.CallAfter()), as there are no guarantees on the
order of execution when events are posted (I have found that the event
queue sometimes behaves like a stack).
I would also suggest never polling any queue from the GUI thread. It's
wasteful. Just have it respond to an event (either explicitly from
wx.PostEvent() or implicitly with wx.CallAfter()).
More information about the Python-list