Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Tutorial

How to Read this Tutorial
Hello, World! (Beginner)
Calling Multiple Slots
Passing Values to and from Slots
Connection Management
Example: Document-View
Giving a Slot Access to its Connection (Advanced)
Changing the Mutex Type of a Signal (Advanced).
Linking against the Signals2 library

How to Read this Tutorial

This tutorial is not meant to be read linearly. Its top-level structure roughly separates different concepts in the library (e.g., handling calling multiple slots, passing values to and from slots) and in each of these concepts the basic ideas are presented first and then more complex uses of the library are described later. Each of the sections is marked Beginner, Intermediate, or Advanced to help guide the reader. The Beginner sections include information that all library users should know; one can make good use of the Signals2 library after having read only the Beginner sections. The Intermediate sections build on the Beginner sections with slightly more complex uses of the library. Finally, the Advanced sections detail very advanced uses of the Signals2 library, that often require a solid working knowledge of the Beginner and Intermediate topics; most users will not need to read the Advanced sections.

Hello, World! (Beginner)

The following example writes "Hello, World!" using signals and slots. First, we create a signal sig, a signal that takes no arguments and has a void return value. Next, we connect the hello function object to the signal using the connect method. Finally, use the signal sig like a function to call the slots, which in turns invokes HelloWorld::operator() to print "Hello, World!".

struct HelloWorld
{
  void operator()() const
  {
    std::cout << "Hello, World!" << std::endl;
  }
};
  // Signal with no arguments and a void return value
  boost::signals2::signal<void ()> sig;

  // Connect a HelloWorld slot
  HelloWorld hello;
  sig.connect(hello);

  // Call all of the slots
  sig();

Calling Multiple Slots

Connecting Multiple Slots (Beginner)

Calling a single slot from a signal isn't very interesting, so we can make the Hello, World program more interesting by splitting the work of printing "Hello, World!" into two completely separate slots. The first slot will print "Hello" and may look like this:

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

The second slot will print ", World!" and a newline, to complete the program. The second slot may look like this:

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

Like in our previous example, we can create a signal sig that takes no arguments and has a void return value. This time, we connect both a hello and a world slot to the same signal, and when we call the signal both slots will be called.

  boost::signals2::signal<void ()> sig;

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

  sig();

By default, slots are pushed onto the back of the slot list, so the output of this program will be as expected:

Hello, World!

Ordering Slot Call Groups (Intermediate)

Slots are free to have side effects, and that can mean that some slots will have to be called before others even if they are not connected in that order. The Boost.Signals2 library allows slots to be placed into groups that are ordered in some way. For our Hello, World program, we want "Hello" to be printed before ", World!", so we put "Hello" into a group that must be executed before the group that ", World!" is in. To do this, we can supply an extra parameter at the beginning of the connect call that specifies the group. Group values are, by default, ints, and are ordered by the integer < relation. Here's how we construct Hello, World:

  boost::signals2::signal<void ()> sig;

  sig.connect(1, World());  // connect with group 1
  sig.connect(0, Hello());  // connect with group 0

Invoking the signal will correctly print "Hello, World!", because the Hello object is in group 0, which precedes group 1 where the World object resides. The group parameter is, in fact, optional. We omitted it in the first Hello, World example because it was unnecessary when all of the slots are independent. So what happens if we mix calls to connect that use the group parameter and those that don't? The "unnamed" slots (i.e., those that have been connected without specifying a group name) can be placed at the front or back of the slot list (by passing boost::signals2::at_front or boost::signals2::at_back as the last parameter to connect, respectively), and default to the end of the list. When a group is specified, the final at_front or at_back parameter describes where the slot will be placed within the group ordering. Ungrouped slots connected with at_front will always precede all grouped slots. Ungrouped slots connected with at_back will always succeed all grouped slots.

If we add a new slot to our example like this:

struct GoodMorning
{
  void operator()() const
  {
    std::cout << "... and good morning!" << std::endl;
  }
};
  // by default slots are connected at the end of the slot list
  sig.connect(GoodMorning());

  // slots are invoked this order:
  // 1) ungrouped slots connected with boost::signals2::at_front
  // 2) grouped slots according to ordering of their groups
  // 3) ungrouped slots connected with boost::signals2::at_back
  sig();

... we will get the result we wanted:

Hello, World!
... and good morning!

Passing Values to and from Slots

Slot Arguments (Beginner)

Signals can propagate arguments to each of the slots they call. For instance, a signal that propagates mouse motion events might want to pass along the new mouse coordinates and whether the mouse buttons are pressed.

As an example, we'll create a signal that passes two float arguments to its slots. Then we'll create a few slots that print the results of various arithmetic operations on these values.

void print_args(float x, float y)
{
  std::cout << "The arguments are " << x << " and " << y << std::endl;
}

void print_sum(float x, float y)
{
  std::cout << "The sum is " << x + y << std::endl;
}

void print_product(float x, float y)
{
  std::cout << "The product is " << x * y << std::endl;
}

void print_difference(float x, float y)
{
  std::cout << "The difference is " << x - y << std::endl;
}

void print_quotient(float x, float y)
{
  std::cout << "The quotient is " << x / y << std::endl;
}
  boost::signals2::signal<void (float, float)> sig;

  sig.connect(&print_args);
  sig.connect(&print_sum);
  sig.connect(&print_product);
  sig.connect(&print_difference);
  sig.connect(&print_quotient);

  sig(5., 3.);

This program will print out the following:

The arguments are 5 and 3
The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667

So any values that are given to sig when it is called like a function are passed to each of the slots. We have to declare the types of these values up front when we create the signal. The type boost::signals2::signal<void (float, float)> means that the signal has a void return value and takes two float values. Any slot connected to sig must therefore be able to take two float values.

Signal Return Values (Advanced)

Just as slots can receive arguments, they can also return values. These values can then be returned back to the caller of the signal through a combiner. The combiner is a mechanism that can take the results of calling slots (there may be no results or a hundred; we don't know until the program runs) and coalesces them into a single result to be returned to the caller. The single result is often a simple function of the results of the slot calls: the result of the last slot call, the maximum value returned by any slot, or a container of all of the results are some possibilities.

We can modify our previous arithmetic operations example slightly so that the slots all return the results of computing the product, quotient, sum, or difference. Then the signal itself can return a value based on these results to be printed:

float product(float x, float y) { return x * y; }
float quotient(float x, float y) { return x / y; }
float sum(float x, float y) { return x + y; }
float difference(float x, float y) { return x - y; }
boost::signals2::signal<float (float, float)> sig;
  sig.connect(&product);
  sig.connect(&quotient);
  sig.connect(&sum);
  sig.connect(&difference);

  // The default combiner returns a boost::optional containing the return
  // value of the last slot in the slot list, in this case the
  // difference function.
  std::cout << *sig(5, 3) << std::endl;

This example program will output 2. This is because the default behavior of a signal that has a return type (float, the first template argument given to the boost::signals2::signal class template) is to call all slots and then return a boost::optional containing the result returned by the last slot called. This behavior is admittedly silly for this example, because slots have no side effects and the result is the last slot connected.

A more interesting signal result would be the maximum of the values returned by any slot. To do this, we create a custom combiner that looks like this:

// combiner which returns the maximum value returned by all slots
template<typename T>
struct maximum
{
  typedef T result_type;

  template<typename InputIterator>
  T operator()(InputIterator first, InputIterator last) const
  {
    // If there are no slots to call, just return the
    // default-constructed value
    if(first == last ) return T();
    T max_value = *first++;
    while (first != last) {
      if (max_value < *first)
        max_value = *first;
      ++first;
    }

    return max_value;
  }
};

The maximum class template acts as a function object. Its result type is given by its template parameter, and this is the type it expects to be computing the maximum based on (e.g., maximum<float> would find the maximum float in a sequence of floats). When a maximum object is invoked, it is given an input iterator sequence [first, last) that includes the results of calling all of the slots. maximum uses this input iterator sequence to calculate the maximum element, and returns that maximum value.

We actually use this new function object type by installing it as a combiner for our signal. The combiner template argument follows the signal's calling signature:

boost::signals2::signal<float (float x, float y),
              maximum<float> > sig;

Now we can connect slots that perform arithmetic functions and use the signal:

  sig.connect(&product);
  sig.connect(&quotient);
  sig.connect(&sum);
  sig.connect(&difference);

  // Outputs the maximum value returned by the connected slots, in this case
  // 15 from the product function.
  std::cout << "maximum: " << sig(5, 3) << std::endl;

The output of this program will be 15, because regardless of the order in which the slots are connected, the product of 5 and 3 will be larger than the quotient, sum, or difference.

In other cases we might want to return all of the values computed by the slots together, in one large data structure. This is easily done with a different combiner:

// aggregate_values is a combiner which places all the values returned
// from slots into a container
template<typename Container>
struct aggregate_values
{
  typedef Container result_type;

  template<typename InputIterator>
  Container operator()(InputIterator first, InputIterator last) const
  {
    Container values;

    while(first != last) {
      values.push_back(*first);
      ++first;
    }
    return values;
  }
};

Again, we can create a signal with this new combiner:

boost::signals2::signal<float (float, float),
    aggregate_values<std::vector<float> > > sig;
  sig.connect(&quotient);
  sig.connect(&product);
  sig.connect(&sum);
  sig.connect(&difference);

  std::vector<float> results = sig(5, 3);
  std::cout << "aggregate values: ";
  std::copy(results.begin(), results.end(),
    std::ostream_iterator<float>(std::cout, " "));
  std::cout << "\n";

The output of this program will contain 15, 8, 1.6667, and 2. It is interesting here that the first template argument for the signal class, float, is not actually the return type of the signal. Instead, it is the return type used by the connected slots and will also be the value_type of the input iterators passed to the combiner. The combiner itself is a function object and its result_type member type becomes the return type of the signal.

The input iterators passed to the combiner transform dereference operations into slot calls. Combiners therefore have the option to invoke only some slots until some particular criterion is met. For instance, in a distributed computing system, the combiner may ask each remote system whether it will handle the request. Only one remote system needs to handle a particular request, so after a remote system accepts the work we do not want to ask any other remote systems to perform the same task. Such a combiner need only check the value returned when dereferencing the iterator, and return when the value is acceptable. The following combiner returns the first non-NULL pointer to a FulfilledRequest data structure, without asking any later slots to fulfill the request:

struct DistributeRequest {
  typedef FulfilledRequest* result_type;

  template<typename InputIterator>
  result_type operator()(InputIterator first, InputIterator last) const
  {
    while (first != last) {
      if (result_type fulfilled = *first)
        return fulfilled;
      ++first;
    }
    return 0;
  }
};

Connection Management

Disconnecting Slots (Beginner)

Slots aren't expected to exist indefinitely after they are connected. Often slots are only used to receive a few events and are then disconnected, and the programmer needs control to decide when a slot should no longer be connected.

The entry point for managing connections explicitly is the boost::signals2::connection class. The connection class uniquely represents the connection between a particular signal and a particular slot. The connected() method checks if the signal and slot are still connected, and the disconnect() method disconnects the signal and slot if they are connected before it is called. Each call to the signal's connect() method returns a connection object, which can be used to determine if the connection still exists or to disconnect the signal and slot.

  boost::signals2::connection c = sig.connect(HelloWorld());
  std::cout << "c is connected\n";
  sig(); // Prints "Hello, World!"

  c.disconnect(); // Disconnect the HelloWorld object
  std::cout << "c is disconnected\n";
  sig(); // Does nothing: there are no connected slots

Blocking Slots (Beginner)

Slots can be temporarily "blocked", meaning that they will be ignored when the signal is invoked but have not been permanently disconnected. This is typically used to prevent infinite recursion in cases where otherwise running a slot would cause the signal it is connected to to be invoked again. A boost::signals2::shared_connection_block object will temporarily block a slot. The connection is unblocked by either destroying or calling unblock on all the shared_connection_block objects that reference the connection. Here is an example of blocking/unblocking slots:

  boost::signals2::connection c = sig.connect(HelloWorld());
  std::cout << "c is not blocked.\n";
  sig(); // Prints "Hello, World!"

  {
    boost::signals2::shared_connection_block block(c); // block the slot
    std::cout << "c is blocked.\n";
    sig(); // No output: the slot is blocked
  } // shared_connection_block going out of scope unblocks the slot
  std::cout << "c is not blocked.\n";
  sig(); // Prints "Hello, World!"}

Scoped Connections (Intermediate)

The boost::signals2::scoped_connection class references a signal/slot connection that will be disconnected when the scoped_connection class goes out of scope. This ability is useful when a connection need only be temporary, e.g.,

  {
    boost::signals2::scoped_connection c(sig.connect(ShortLived()));
    sig(); // will call ShortLived function object
  } // scoped_connection goes out of scope and disconnects

  sig(); // ShortLived function object no longer connected to sig

Note, attempts to initialize a scoped_connection with the assignment syntax will fail due to it being noncopyable. Either the explicit initialization syntax or default construction followed by assignment from a signals2::connection will work:

// doesn't compile due to compiler attempting to copy a temporary scoped_connection object
// boost::signals2::scoped_connection c0 = sig.connect(ShortLived());

// okay
boost::signals2::scoped_connection c1(sig.connect(ShortLived()));

// also okay
boost::signals2::scoped_connection c2;
c2 = sig.connect(ShortLived());

Disconnecting Equivalent Slots (Intermediate)

One can disconnect slots that are equivalent to a given function object using a form of the signal::disconnect method, so long as the type of the function object has an accessible == operator. For instance:

void foo() { std::cout << "foo"; }
void bar() { std::cout << "bar\n"; }
boost::signals2::signal<void ()> sig;
  sig.connect(&foo);
  sig.connect(&bar);
  sig();

  // disconnects foo, but not bar
  sig.disconnect(&foo);
  sig();

Automatic Connection Management (Intermediate)

Boost.Signals2 can automatically track the lifetime of objects involved in signal/slot connections, including automatic disconnection of slots when objects involved in the slot call are destroyed. For instance, consider a simple news delivery service, where clients connect to a news provider that then sends news to all connected clients as information arrives. The news delivery service may be constructed like this:

class NewsItem { /* ... */ };

typedef boost::signals2::signal<void (const NewsItem&)> signal_type;
signal_type deliverNews;

Clients that wish to receive news updates need only connect a function object that can receive news items to the deliverNews signal. For instance, we may have a special message area in our application specifically for news, e.g.,:

struct NewsMessageArea : public MessageArea
{
public:
  // ...

  void displayNews(const NewsItem& news) const
  {
    messageText = news.text();
    update();
  }
};

// ...
NewsMessageArea *newsMessageArea = new NewsMessageArea(/* ... */);
// ...
deliverNews.connect(boost::bind(&NewsMessageArea::displayNews,
  newsMessageArea, _1));

However, what if the user closes the news message area, destroying the newsMessageArea object that deliverNews knows about? Most likely, a segmentation fault will occur. However, with Boost.Signals2 one may track any object which is managed by a shared_ptr, by using slot::track. A slot will automatically disconnect when any of its tracked objects expire. In addition, Boost.Signals2 will ensure that no tracked object expires while the slot it is associated with is in mid-execution. It does so by creating temporary shared_ptr copies of the slot's tracked objects before executing it. To track NewsMessageArea, we use a shared_ptr to manage its lifetime, and pass the shared_ptr to the slot via its slot::track method before connecting it, e.g.:

// ...
boost::shared_ptr<NewsMessageArea> newsMessageArea(new NewsMessageArea(/* ... */));
// ...
deliverNews.connect(signal_type::slot_type(&NewsMessageArea::displayNews,
  newsMessageArea.get(), _1).track(newsMessageArea));

Note there is no explicit call to bind() needed in the above example. If the signals2::slot constructor is passed more than one argument, it will automatically pass all the arguments to bind and use the returned function object.

Also note, we pass an ordinary pointer as the second argument to the slot constructor, using newsMessageArea.get() instead of passing the shared_ptr itself. If we had passed the newsMessageArea itself, a copy of the shared_ptr would have been bound into the slot function, preventing the shared_ptr from expiring. However, the use of slot::track implies we wish to allow the tracked object to expire, and automatically disconnect the connection when this occurs.

shared_ptr classes other than boost::shared_ptr (such as std::shared_ptr) may also be tracked for connection management purposes. They are supported by the slot::track_foreign method.

Postconstructors and Predestructors (Advanced)

One limitation of using shared_ptr for tracking is that an object cannot setup tracking of itself in its constructor. However, it is possible to set up tracking in a post-constructor which is called after the object has been created and passed to a shared_ptr. The Boost.Signals2 library provides support for post-constructors and pre-destructors via the deconstruct() factory function.

For most cases, the simplest and most robust way to setup postconstructors for a class is to define an associated adl_postconstruct function which can be found by deconstruct(), make the class' constructors private, and give deconstruct access to the private constructors by declaring deconstruct_access a friend. This will ensure that objects of the class may only be created through the deconstruct() function, and their associated adl_postconstruct() function will always be called.

The examples section contains several examples of defining classes with postconstructors and predestructors, and creating objects of these classes using deconstruct()

Be aware that the postconstructor/predestructor support in Boost.Signals2 is in no way essential to the use of the library. The use of deconstruct is purely optional. One alternative is to define static factory functions for your classes. The factory function can create an object, pass ownership of the object to a shared_ptr, setup tracking for the object, then return the shared_ptr.

When Can Disconnections Occur? (Intermediate)

Signal/slot disconnections occur when any of these conditions occur:

  • The connection is explicitly disconnected via the connection's disconnect method directly, or indirectly via the signal's disconnect method, or scoped_connection's destructor.

  • An object tracked by the slot is destroyed.

  • The signal is destroyed.

These events can occur at any time without disrupting a signal's calling sequence. If a signal/slot connection is disconnected at any time during a signal's calling sequence, the calling sequence will still continue but will not invoke the disconnected slot. Additionally, a signal may be destroyed while it is in a calling sequence, in which case it will complete its slot call sequence but may not be accessed directly.

Signals may be invoked recursively (e.g., a signal A calls a slot B that invokes signal A...). The disconnection behavior does not change in the recursive case, except that the slot calling sequence includes slot calls for all nested invocations of the signal.

Note, even after a connection is disconnected, its's associated slot may still be in the process of executing. In other words, disconnection does not block waiting for the connection's associated slot to complete execution. This situation may occur in a multi-threaded environment if the disconnection occurs concurrently with signal invocation, or in a single-threaded environment if a slot disconnects itself.

Passing Slots (Intermediate)

Slots in the Boost.Signals2 library are created from arbitrary function objects, and therefore have no fixed type. However, it is commonplace to require that slots be passed through interfaces that cannot be templates. Slots can be passed via the slot_type for each particular signal type and any function object compatible with the signature of the signal can be passed to a slot_type parameter. For instance:

// a pretend GUI button
class Button
{
  typedef boost::signals2::signal<void (int x, int y)> OnClick;
public:
  typedef OnClick::slot_type OnClickSlotType;
  // forward slots through Button interface to its private signal
  boost::signals2::connection doOnClick(const OnClickSlotType & slot);

  // simulate user clicking on GUI button at coordinates 52, 38
  void simulateClick();
private:
  OnClick onClick;
};

boost::signals2::connection Button::doOnClick(const OnClickSlotType & slot)
{
  return onClick.connect(slot);
}

void Button::simulateClick()
{
  onClick(52, 38);
}

void printCoordinates(long x, long y)
{
  std::cout << "(" << x << ", " << y << ")\n";
}
  Button button;
  button.doOnClick(&printCoordinates);
  button.simulateClick();

The doOnClick method is now functionally equivalent to the connect method of the onClick signal, but the details of the doOnClick method can be hidden in an implementation detail file.

Example: Document-View

Signals can be used to implement flexible Document-View architectures. The document will contain a signal to which each of the views can connect. The following Document class defines a simple text document that supports mulitple views. Note that it stores a single signal to which all of the views will be connected.

class Document
{
public:
    typedef boost::signals2::signal<void ()>  signal_t;

public:
    Document()
    {}

    /* Connect a slot to the signal which will be emitted whenever
      text is appended to the document. */
    boost::signals2::connection connect(const signal_t::slot_type &subscriber)
    {
        return m_sig.connect(subscriber);
    }

    void append(const char* s)
    {
        m_text += s;
        m_sig();
    }

    const std::string& getText() const
    {
        return m_text;
    }

private:
    signal_t    m_sig;
    std::string m_text;
};

Next, we can begin to define views. The following TextView class provides a simple view of the document text.

class TextView
{
public:
    TextView(Document& doc): m_document(doc)
    {
        m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
    }

    ~TextView()
    {
        m_connection.disconnect();
    }

    void refresh() const
    {
        std::cout << "TextView: " << m_document.getText() << std::endl;
    }
private:
    Document&               m_document;
    boost::signals2::connection  m_connection;
};

Alternatively, we can provide a view of the document translated into hex values using the HexView view:

class HexView
{
public:
    HexView(Document& doc): m_document(doc)
    {
        m_connection = m_document.connect(boost::bind(&HexView::refresh, this));
    }

    ~HexView()
    {
        m_connection.disconnect();
    }

    void refresh() const
    {
        const std::string&  s = m_document.getText();

        std::cout << "HexView:";

        for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
            std::cout << ' ' << std::hex << static_cast<int>(*it);

        std::cout << std::endl;
    }
private:
    Document&               m_document;
    boost::signals2::connection  m_connection;
};

To tie the example together, here is a simple main function that sets up two views and then modifies the document:

int main(int argc, char* argv[])
{
    Document    doc;
    TextView    v1(doc);
    HexView     v2(doc);

    doc.append(argc == 2 ? argv[1] : "Hello world!");
    return 0;
}

The complete example source, contributed by Keith MacDonald, is available in the examples section. We also provide variations on the program which employ automatic connection management to disconnect views on their destruction.

Giving a Slot Access to its Connection (Advanced)

You may encounter situations where you wish to disconnect or block a slot's connection from within the slot itself. For example, suppose you have a group of asynchronous tasks, each of which emits a signal when it completes. You wish to connect a slot to all the tasks to retrieve their results as each completes. Once a given task completes and the slot is run, the slot no longer needs to be connected to the completed task. Therefore, you may wish to clean up old connections by having the slot disconnect its invoking connection when it runs.

For a slot to disconnect (or block) its invoking connection, it must have access to a signals2::connection object which references the invoking signal-slot connection. The difficulty is, the connection object is returned by the signal::connect method, and therefore is not available until after the slot is already connected to the signal. This can be particularly troublesome in a multi-threaded environment where the signal may be invoked concurrently by a different thread while the slot is being connected.

Therefore, the signal classes provide signal::connect_extended methods, which allow slots which take an extra argument to be connected to a signal. The extra argument is a signals2::connection object which refers to the signal-slot connection currently invoking the slot. signal::connect_extended uses slots of the type given by the signal::extended_slot_type typedef.

The examples section includes an extended_slot program which demonstrates the syntax for using signal::connect_extended.

Changing the Mutex Type of a Signal (Advanced).

For most cases the default type of boost::signals2::mutex for a signals2::signal's Mutex template type parameter should be fine. If you wish to use an alternate mutex type, it must be default-constructible and fulfill the Lockable concept defined by the Boost.Thread library. That is, it must have lock() and unlock() methods (the Lockable concept also includes a try_lock() method but this library does not require try locking).

The Boost.Signals2 library provides one alternate mutex class for use with signal: boost::signals2::dummy_mutex. This is a fake mutex for use in single-threaded programs, where locking a real mutex would be useless overhead. Other mutex types you could use with signal include boost::mutex, or the std::mutex from C++11.

Changing a signal's Mutex template type parameter can be tedious, due to the large number of template parameters which precede it. The signal_type metafunction is particularly useful in this case, since it enables named template type parameters for the signals2::signal class. For example, to declare a signal which takes an int as an argument and uses a boost::signals2::dummy_mutex for its Mutex types, you could write:

namespace bs2 = boost::signals2;
using namespace bs2::keywords;
bs2::signal_type<void (int), mutex_type<bs2::dummy_mutex> >::type sig;

Linking against the Signals2 library

Unlike the original Boost.Signals library, Boost.Signals2 is currently header-only.


PrevUpHomeNext