开发者

How do I make functions run by g_idle_add/g_timeout_add work asynchronously?

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜