473,320 Members | 2,000 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Multiple threads in a GUI app (wxPython), communication between worker thread and app?

This is a network app, written in wxPython and the socket module. This
is what I want to happen:

GUI app starts. User clicks a button to 'start' the work of the app.
When start is pressed, a new thread is spawned (threading module) and
this thread starts listening for data on a socket. When someone
connects, a new thread is spawned, It needs to do I/O on that socket
and open a GUI window so the user can communicate with the client
(socket) that just connected. Any further data that comes in on that
socket should be redirected to the newly opened GUI window. Any more
connection attempts will open a new GUI window and the same cycle
repeats.

How would I get the worker thread to open a GUI window in the main GUI
thread? After that GUI window is open, how can I send and recv messages
from/to the GUI window?

Jul 19 '05 #1
5 10626
"fooooo" <ph*****@yahoo.com> writes:
How would I get the worker thread to open a GUI window in the main GUI
thread? After that GUI window is open, how can I send and recv messages
from/to the GUI window?


First of all the favorite Pythonic way to communicate between threads
is with synchronized queues--see the Queue module. Have the worker
thread put stuff on a queue and have the main GUI thread read from it.

Secondly, I don't know about wxPython, but in tkinter you have to
resort to a kludge in order for the gui thread to handle gui events
and also notice stuff on a queue. There's a tkinter command to run
some function after a specified time (say 50 msec). So you'd set that
timeout to check the queue and restart the timer, which means the gui
would check 20x a second for updates from the worker threads. When it
got such an update, it would create a new window or whatever.

It could be that wxPython has a cleaner way of doing this, or you
might have to do something similar. Python thread support seems to
have been something of an afterthought and there's a lot of weirdness
like this to deal with.
Jul 19 '05 #2
"fooooo" <ph*****@yahoo.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
This is a network app, written in wxPython and the socket module. This
is what I want to happen:


I'm not sure if this will help you, but it solved what was, for me, a
more general problem: not (normally) being able to issue wxPython calls
outside the GUI thread.

I came up with a general-purpose thread-switcher, which, given a
callable, would on invocation:
queue itself up on the GUI event queue
call its callable in the GUI thread (allowing arbitrary wxPython
calls)
pass its result back to the calling thread (or re-raise any exception
there).

Instead of having a dedicated queue, it uses one already in place.
Because all calls using it are serialized, it had the beneficial
side-effect (for me, anyway)of avoiding certain concurrency issues.

(The calls to my locks module, CheckPause() and CheckCancel(), were
there so the user could suspend, resume, and cancel worker threads at
will, which the Python threading module does not naturally support(my
locks module held some state that could be set via the GUI.) If you have
no need of that, delete those lines and everything should still work
(they were a late addition).

import wx, threading, types
import locks # my code, see remark above

#-------------------------------------
# decorator used to call a method (or other callable)
# from the wxPython main thread (with appropriate switching)
#--------------------------------------
class wxThreadSwitch(object):
def __init__(self, callable):
object.__init__(self)
self.callable = callable

def __get__(self, inst, owner=None):
c = self.callable
# if c is a descriptor then wrap it around
# the instance as would have happened normally
if not isinstance(c, types.InstanceType):
try:
get = c.__get__
args = [inst]
if owner is not None:
args.append(owner)
return wxThreadSwitch(get(*args))
except AttributeError:
pass
# if we get here, then not a descriptor,
# so return self unchanged
return self

def __call__(self, *args, **kwargs):
if wx.Thread_IsMain():
return self.callable(*args, **kwargs)

locks.CheckPause()
c = self.__wxThreadCall(self.callable)
wx.CallAfter(c, *args, **kwargs)
return c.Result()

class __wxThreadCall(object):
def __init__(self, callable):
assert not wx.Thread_IsMain()
object.__init__(self)
self.callable = callable
self.result = None
self.exc_info = None
self.event = threading.Event()

def __call__(self, *args, **kwargs):
try:
try:
assert wx.Thread_IsMain()
assert not self.event.isSet()
locks.CheckCancel()
self.result = self.callable(*args, **kwargs)
except:
self.exc_info = sys.exc_info()
finally:
self.event.set()

def Result(self):
self.event.wait()
if self.exc_info:
type, value, traceback = self.exc_info
raise type, value, traceback
return self.result
A usage example would be to decorate a function or method with it:

class Something:
@wxThreadSwitch
def someGUICallOrOther():
....
Here the method call would run via the wxThreadSwitch decorator which
would do any necessary thread switching.

Hope this helps

John
Jul 19 '05 #3
Look inthe demo that comes with wxPython it is in tree process and
events -> threads .
There is a nice demo of PostEvent().
Another way would be to use Queues as others have mention .
You can create a new frame and have it call the queue for data.

M.E.Farmer

Jul 19 '05 #4
Thanks for the replies. I have a Queue object in the main GUI thread,
this gets passed to all the worker threads and they add items to it.
This is all well and good, but what is a good way to get the GUI thread
to send items back to the worker threads?

Jul 19 '05 #5
"fooooo" <ph*****@yahoo.com> writes:
Thanks for the replies. I have a Queue object in the main GUI thread,
this gets passed to all the worker threads and they add items to it.
This is all well and good, but what is a good way to get the GUI thread
to send items back to the worker threads?


Use another Queue.
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Andrae Muys | last post by:
Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next...
1
by: Dr. Len | last post by:
Hi all! In my app I implemented a separate worker thread that handles network communication using Net.Sockets. It needs to make updates to a DataTable object, which is displayed to the user by a...
9
by: perchef | last post by:
Hi, I have several files to download and a GUI to update. I know this is a frequently asked question but i can't find an appropriate solution. My Downloader extends threading.Thread and update a...
6
by: m | last post by:
Hello, I have an application that processes thousands of files each day. The filenames and various related file information is retrieved, related filenames are associate and placed in a linked...
2
by: Hollywood | last post by:
I have a system in which I have a single thread that places data on a Queue. Then I have one worker thread that waits until data is put on the thread and dequeues the Queue and processes that...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
9
by: zxo102 | last post by:
Hi everyone, I am using a python socket server to collect data from a socket client and then control a image location ( wxpython) with the data, i.e. moving the image around in the wxpython frame....
5
by: Benjamin | last post by:
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...
3
by: scriptlearner | last post by:
I am trying to put up a queue (through a logging thread) so that all worker threads can ask it to log messages. However, the problem I am facing is that, well, the logging thread itself is running...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.