Are boost::signals slots called synchronously or asynchronously?
Asked Answered
R

2

7

Can anyone tell me are boost::signals slots called synchronously or asynchronously?

For example I have this piece of code:

struct Hello
{
  void operator()() const
  {
    std::cout << "Hello ";
  }
};

struct World
{
  void operator()() const
  {
    std::cout << " world!" << std::endl;
  }
};

boost::signal<void ()> sig;

sig.connect(Hello());
sig.connect(World());

sig();

cout << "Foo";

How does the execution thread work? Does the execution wait for Hello() and World() to execute and just after that "Foo" is printed or does it call them asynchronously(printing "Foo" and calling Hello() and World() execute in an undefined order)?

Resistless answered 8/2, 2013 at 12:15 Comment(0)
M
9

In Boost.Signals slots are called synchronously and slots connected to the same signal are called in the order in which they were added. This is true also of the thread-safe variant, Boost.Signals2

Meridethmeridian answered 8/2, 2013 at 12:59 Comment(2)
Docs here seem to indicate otherwise: boost.org/doc/libs/1_54_0/doc/html/signals2/…Robinet
You are right. I was convinced that the order wasn't specified, but that portion of the documentation hasn't changed in the last four or five releases. I corrected my answer.Meridethmeridian
E
0

This should print "Hello World Foo" but could legally print "World Hello Foo" because the order of calls to multiple connected slots is not defined AFAIK.

If you want strict order use this syntax:

sig.connect(1, World());
sig.connect(0, Hello());
Eskill answered 8/2, 2013 at 12:43 Comment(1)
I understand but what I need to know is if there is any chance of printing Foo Hello World or Hello Foo World or World Foo Hello or any intercalation between Foo and the slots. Can the slots execute asynchronously or not?Resistless

© 2022 - 2024 — McMap. All rights reserved.