What is the proper way of implementing threading in a GTK application?

Viewed 31

I am aware that this is quite a vague question, but bear with me. When trying to add threading to GTK applications, I often find my implementation to be quite cumbersome. Take an example where upon pressing a button, example_function gets called. This function calls other functions, performs a long calculation, then calls GTK code. Point is that this function performs a lot of different tasks.

The question is, how should a function (example_function) be structured? Should the entire function be moved to a separate thread, with all code that updates the UI moved into separate functions and called using GLib.idle_add? Or should it run on the main thread with only the long-taking code moved into a separate function, and having that threaded - if this were the case, then how should sequentiality be handled?

Take the following non-threaded function:

def main_function(self, widget):
    print('start of main_function')

    output = self.long_function(example_argument)
    self.button.set_label(label=output)
    print('label set')

    self.another_function()
    print('end of main_function')

What would be the post optimal way of adding threading to such a function, while maintaining sequentiality. Ideally, all calculations would be moved off the main UI thread.

0 Answers
Related