Tkinter/Python threading issue

Status
You're currently viewing only Stanley Turnteen's posts. Click here to go back to viewing the entire thread.
Not open for further replies.
I don't know anything about Tkinter, but you don't have a threading issue. You're using multiple processes, which don't have access to each other's resources, requiring some form of IPC to communicate. You're on the right track with pipes - I'd probably use UNIX domain sockets, but have a look at http://docs.python.org/library/ipc.html for a list of the available options.

Also, note that in general, most GUI toolkits require that UI updates occur in the primary thread (e.g. BeginInvoke(), -performSelectorOnMainThread:withObject:), so even if you were using threads, you'd likely have to do a bit of work to marshal your label update action onto the main thread.
 
Calling os.read() will block until data or EOF is received (unless the fd is opened with os.O_NONBLOCK), leaving Tkinter unable to process any GUI events. You need to integrate with the toolkit's event loop.

A quick glance at the Tk docs indicates something like this should work:

Code:
# Somewhere in your app's initialization code
from Tkinter import *
app = Tk()

# Schedule the check_message() method to run as often as possible
app.after(0, check_message)
app.mainloop()

The after() method schedules the specified task to run exactly once, so call it again at the end of check_message(). Be sure to open the fd with os.O_NONBLOCK; if there is no data to read, it will return immediately, letting Tkinter process other events. If you don't need to spin as fast as possible watching for messages, increase the first parameter to after() as desired.
 
os.fdopen() doesn't take flags, only os.open() does.

os.fdopen(fd[, mode[, bufsize]])
Return an open file object connected to the file descriptor fd. The mode and bufsize arguments have the same meaning as the corresponding arguments to the built-in open() function.

Calling os.fdopen(client_receive, 'r', os.O_NONBLOCK) is actually setting bufsize to whatever the constant for os.O_NONBLOCK is (on my system, it's 4). Since you are using os.pipe(), you already have an fd, so you'll need to use fcntl to set options on it:

Code:
import fcntl
r, w = os.pipe()
if fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK) != 0:
  # handle error

# Call os.fdopen() on r, or just use os.read() like you did in your earlier code
 
On Linux, errno 11 is EAGAIN (it's 35 on Mac OS X, but that's what the errno module is for). From read(2):

[EAGAIN] The file was marked for non-blocking I/O, and no data were ready to be read.

Just trap that with a try/except block:

Code:
import errno

try:
  incoming_data = os.read(self.client_receive, 1024)
except OSError, e:
  if e.errno == errno.EAGAIN:
    # No data waiting
    pass
  else:
    raise
 
Status
You're currently viewing only Stanley Turnteen's posts. Click here to go back to viewing the entire thread.
Not open for further replies.