开发者

are glib signals asynchronous?

When using glib to dispatch signals through emit, are all the "listeners"/handlers called back-to-back or is control relinquished to the even开发者_运维技巧t loop after each listener/handler?


The callbacks are all called back-to-back without relinquishing control to the main loop.

Actually, as far as I know, g_signal_emit() does not even return control until all handlers are called, so there is no opportunity for the main-loop to kick-in.

So to answer the question in the title of this post: no, glib signals are not asynchronous.


GLib signals can be handled synchronously or asynchronously. GObject signals are always synchronous, i.e. when you emit a signal it does not return until the signal is handled. To have a signal asynchronously handled with GLib, (I am using vala for brevity - use the vala compiler to convert the code into plain C) you must define a signal Source, or use a predefined one, as for example IdleSource or TimeoutSource (when I/O is out of question). For example assume that you have a function

void my_func() {
  stdout.puts("Hello world! (async)\n");
}

and you want to call it asynchronously (from the same thread!) from

void caller() {
  // Here you want to insert the asynchronous call
  // that will be invoked AFTER caller has returned.
  // Body of caller follows:
  stdout.puts("Hello world!\n");
}

Here is how you do it:

void caller() {
  // Code for the asynchronous call:
  var ev = new IdleSource();
  ev.set_callback(() => {
    my_func();
    return Source.REMOVE; // Source.REMOVE = false
  });
  ev.attach(MainContext.default());
  // Body of caller follows:
  stdout.puts("Hello world!\n");
}

You will get the following output:

Hello world!
Hello world! (async)

The my_func() function will be executed when MainLoop is idle (i.e. it has no other signals to process). To trigger it after a specific time interval has elapsed use the TimeoutSource signal source. A MainLoop must be running, otherwise this will not work.

Documentation:

  • https://valadoc.org/glib-2.0/index.htm
  • https://developer.gnome.org/glib/stable/glib-The-Main-Event-Loop.html
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜