2
votes

I intend to write a networking application with a GUI frontend, presumably using GTK.

I'm completely new to GTK (and GUI programming in general). My current guess would be to use two threads, one that handles networking and the other one running the GTK frontend.

Is this the common design pattern for this kind of problem or are there better alternatives, e.g. handling networking from within the GTK main loop?

If I have to resort to using two threads, what's the best way to tell the GTK thread that there's data available from the networking thread?

2

2 Answers

3
votes

The normal GTK+ way of doing things is to have your GUI on the main thread, while slow operations are done on other thread(s). Note that when you want to update the GUI from another thread, you have to do it inside the GDK lock. The documentation mentions that "with the Win32 backend, GDK calls should not be attempted from multiple threads at all", but it can be worked around with g_idle_add, which queues the call on the GUI thread.

You can use async GIO functions (e.g. g_input_stream_read_async) for your network operations, but there's nothing stopping you from using a generic threading library, for example:

gtk.gdk.threads_init()

...

def on_button_clicked(button):
    label.set_text("Doing something...")
    threading.Thread(target=do_something).start()

def do_something():
    time.sleep(2)
    glib.idle_add(label.set_text, "Done")

There's a somewhat similar example using C (Pthreads) in the previously-linked GDK Threads documentation.

1
votes

First thing to read up on in GUI programming is the Model View Controller pattern. You want to separate the data flow from the GUI as much as possible. The networking code updates the data model. When the data model has changed, it signals the front end so the GUI can redraw.