g_timeout_add (100, (GSourceFunc) read_next_packets, NULL);
I can feel the GUI resp开发者_Go百科onse is slow because of the above statement.
How can I make it work asynchronously so that it doesn't affect the GUI response?
Callbacks of these functions are called in the main thread. If read_next_packets
is slow or blocks for I/O, you should instead create a separate thread for it that doesn't interfere with GUI. When that thread needs to inform the main thread of something, then it can use g_idle_add
to transfer execution to the main thread 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);
}
精彩评论