How to execute functions executed by g_idle_add / g_timeout_add asynchronously?

g_timeout_add (100, (GSourceFunc) read_next_packets, NULL);

      

I feel like the GUI response is slow due to the above statement.

How can I make it work asynchronously so that it doesn't affect the GUI response?

+2


a source to share


1 answer


The callbacks of these functions are called on the main thread. If it is read_next_packets

running slowly or blocking I / O, you should create a separate thread for it that does not interfere with the GUI. When this thread needs to tell the main thread something, then it can use it g_idle_add

to push execution to the main thread's scope.

In pseudocode:



// In a dedicated thread:
while (...) {
    Package*  package = do_read ();  // This call is slow or blocks.
    if (package)
        g_idle_add ((GSourceFunc) process_package, package);
}

// This is called in the main thread.  Should be fast to not freeze GUI.
gboolean
process_package (Package* package)
{
    ...
    package_free (package);
}

      

+3


a source







All Articles