6

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)?

Jacob Krieg
  • 2,834
  • 15
  • 68
  • 140

2 Answers2

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

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55
  • 1
    Docs here seem to indicate otherwise: http://www.boost.org/doc/libs/1_54_0/doc/html/signals2/tutorial.html#idp164798944 – sje397 Aug 26 '13 at 03:44
  • 1
    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. – Nicola Musatti Aug 26 '13 at 07:49
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());
odinthenerd
  • 5,422
  • 1
  • 32
  • 61
  • 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? – Jacob Krieg Feb 08 '13 at 12:51