Update of /cvsroot/boost-sandbox/boost-sandbox/libs/thread_safe_signals/doc In directory sc8-pr-cvs3.sourceforge.net:/tmp/cvs-serv5908/doc Added Files: design.xml faq.xml introduction.xml rationale.xml signals.xml tests.xml tutorial.xml Log Message: Moved docs from libs/signals/doc. Updated to reflect some of the more recent changes. --- NEW FILE: faq.xml --- <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE section PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <section last-revision="$Date: 2007/03/05 19:54:28 $"> <title>Frequently Asked Questions</title> <qandaset> <qandaentry> <question> <para>Don't noncopyable signal semantics mean that a class with a signal member will be noncopyable as well?</para> </question> <answer> <para>No. The compiler will not be able to generate a copy constructor or copy assignment operator for your class if it has a signal as a member, but you are free to write your own copy constructor and/or copy assignment operator. Just don't try to copy the signal.</para> </answer> </qandaentry> <qandaentry> <question> <para>Is Boost.Signals thread-safe?</para> </question> <answer> <para>Yes, if the ThreadingModel template parameter of the signal is set to boost::signals::multi_threaded. If you use thread-safe signals in your code, you will also have to link to libboost_thread.</para> </answer> </qandaentry> <qandaentry> <question> <para>How do I get Boost.Signals to work with Qt?</para> </question> <answer> <para>When building with Qt, the Moc keywords <code>signals</code> and <code>slots</code> are defined using preprocessor macros, causing programs using Boost.Signals and Qt together to fail to compile.</para> <para><emphasis>For Qt 4.1 and later</emphasis>, This behavior can be turned off in Qt on a per-project or per-file basis with the <code>no_keywords</code> option. This works with out-of-the-box builds of Boost and Qt. You do not need to re-configure, re-build, or duplicate existing libraries. For a project where you want to use both Boost.Signals and Qt Signals and Slots, the relevant part of your .pro file might look like this:</para> <programlisting> CONFIG += no_keywords # so Qt won't #define any non-all-caps `keywords' INCLUDEPATH += . /usr/local/include/boost-1_33_1/ macx:LIBS += /usr/local/lib/libboost_signals-1_33_1.a # ...your exact paths may vary </programlisting> <para>Now you can mix Boost.Signals and Qt Signals and Slots in the same files, and even within the same class or function. You will have to use the upper-case versions of Qt macros in your own code. See the article <ulink url="http://scottcollins.net/articles/a-deeper-look-at-signals-and-slots.html">A Deeper Look at Signals and Slots</ulink> [off-site] for more complete examples and a survey of the strengths of the two systems.</para> <para><emphasis>Older versions of Qt</emphasis> did not provide a reliable mechanism for avoiding these unfriendly, all lower-case `keyword'-like macros. Although this is a problem with Qt and not Boost.Signals, a user can use the two systems together with a little extra effort. There are two ways to do this:</para> <para>The first way involves defining the <code>BOOST_SIGNALS_NAMESPACE</code> macro to some other identifier (e.g., <code>signalslib</code>) when building and using the Boost.Signals library. Then the namespace of the Boost.Signals library will be <code>boost::BOOST_SIGNALS_NAMESPACE</code> instead of <code>boost::signals</code>. To retain the original namespace name in translation units that do not interact with Qt, you can use a namespace alias:</para> <programlisting> namespace boost { namespace signals = BOOST_SIGNALS_NAMESPACE; } </programlisting> <para>The second way, provided by Frank Hess, involves creating a header <code>signalslib.hpp</code> that contains the following code:</para> <programlisting>#ifdef signals #error "signalslib.hpp must be included before any qt header" #endif #include <boost/signal.hpp> namespace boost { namespace signalslib = signals; }</programlisting> <para>This header must be included before any Qt headers. Once it has been included, you can refer to the Signals library via the namespace <code>boost::signalslib</code>. This option is preferable to the first option because it can be used without recompiling the Signals library binary. </para> </answer> </qandaentry> </qandaset> </section> --- NEW FILE: rationale.xml --- <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE section PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <section last-revision="$Date: 2007/03/05 19:54:28 $"> <title>Design Rationale</title> <using-namespace name="boost"/> <using-namespace name="boost::signals"/> <using-class name="boost::signalN"/> <section> <title>Choice of Slot Definitions</title> <para> The definition of a slot differs amongst signals and slots libraries. Within Boost.Signals, a slot is defined in a very loose manner: it can be any function object that is callable given parameters of the types specified by the signal, and whose return value is convertible to the result type expected by the signal. However, alternative definitions have associated pros and cons that were considered prior to the construction of Boost.Signals.</para> <itemizedlist> <listitem> <para><emphasis role="bold">Slots derive from a specific base class</emphasis>: generally a scheme such as this will require all user-defined slots to derive from some library-specified <code>Slot</code> abstract class that defines a virtual function calling the slot. Adaptors can be used to convert a definition such as this to a definition similar to that used by Boost.Signals, but the use of a large number of small adaptor classes containing virtual functions has been found to cause an unacceptable increase in the size of executables (polymorphic class types require more code than non-polymorphic types).</para> <para> This approach does have the benefit of simplicity of implementation and user interface, from an object-oriented perspective.</para> </listitem> <listitem> <para><emphasis role="bold">Slots constructed from a set of primitives</emphasis>: in this scheme the slot can have a limited set of types (often derived from a common abstract base class) that are constructed from some library-defined set of primitives that often include conversions from free function pointers and member function pointers, and a limited set of binding capabilities. Such an approach is reasonably simple and cover most common cases, but it does not allow a large degree of flexibility in slot construction. Libraries for function object composition have become quite advanced and it is out of the scope of a signals and slots library to encorporate such enhancements. Thus Boost.Signals does not include argument binding or function object composition primitives, but instead provides a hook (via the <code><functionname>visit_each</functionname></code> mechanism) that allows existing binder/composition libraries to provide the necessary information to Signals.</para> </listitem> </itemizedlist> <para> Users not satisfied with the slot definition choice may opt to replace the default slot function type with an alternative that meets their specific needs.</para> </section> <section> <title>User-level Connection Management</title> <para> Users need to have fine control over the connection of signals to slots and their eventual disconnection. The approach taken by Boost.Signals is to return a <code><classname>connection</classname></code> object that enables connected/disconnected query, manual disconnection, and an automatic disconnection on destruction mode. Some other possible interfaces include:</para> <itemizedlist> <listitem> <para><emphasis role="bold">Pass slot to disconnect</emphasis>: in this interface model, the disconnection of a slot connected with <code>sig.<methodname>connect</methodname>(slot)</code> is performed via <code>sig.<methodname>disconnect</methodname>(slot)</code>. Internally, a linear search using slot comparison is performed and the slot, if found, is removed from the list. Unfortunately, querying connectedness will generally also end up as linear-time operations. This model also fails for implementation reasons when slots become more complex than simple function pointers, member function pointers and a limited set of compositions and argument binders: to match the slot given in the call to <code><methodname>disconnect</methodname></code> with an existing slot we would need to be able to compare arbitrary function objects, which is not feasible.</para> </listitem> <listitem> <para><emphasis role="bold">Pass a token to disconnect</emphasis>: this approach identifies slots with a token that is easily comparable (e.g., a string), enabling slots to be arbitrary function objects. While this approach is essentially equivalent to the approach taken by Boost.Signals, it is possibly more error-prone for several reasons:</para> <itemizedlist> <listitem> <para>Connections and disconnections must be paired, so the problem becomes similar to the problems incurred when pairing <code>new</code> and <code>delete</code> for dynamic memory allocation. While errors of this sort would not be catastrophic for a signals and slots implementation, their detection is generally nontrivial.</para> </listitem> <listitem> <para>Tokens must be unique, otherwise two slots will have the same name and will be indistinguishable. In environments where many connections will be made dynamically, name generation becomes an additional task for the user. Uniqueness of tokens also results in an additional failure mode when attempting to connect a slot using a token that has already been used.</para> </listitem> <listitem> <para>More parameterization would be required, because the token type must be user-defined. Additional parameterization steepens the learning curver and overcomplicates a simple interface.</para> </listitem> </itemizedlist> <para> This type of interface is supported in Boost.Signals via the slot grouping mechanism. It augments the <code><classname>connection</classname></code> object-based connection management scheme.</para> </listitem> </itemizedlist> </section> <section> <title>Combiner Interface</title> <para> The Combiner interface was chosen to mimic a call to an algorithm in the C++ standard library. It is felt that by viewing slot call results as merely a sequence of values accessed by input iterators, the combiner interface would be most natural to a proficient C++ programmer. Competing interface design generally required the combiners to be constructed to conform to an interface that would be customized for (and limited to) the Signals library. While these interfaces are generally enable more straighforward implementation of the signals & slots libraries, the combiners are unfortunately not reusable (either in other signals & slots libraries or within other generic algorithms), and the learning curve is steepened slightly to learn the specific combiner interface.</para> <para> The Signals formulation of combiners is based on the combiner using the "pull" mode of communication, instead of the more complex "push" mechanism. With a "pull" mechanism, the combiner's state can be kept on the stack and in the program counter, because whenever new data is required (i.e., calling the next slot to retrieve its return value), there is a simple interface to retrieve that data immediately and without returning from the combiner's code. Contrast this with the "push" mechanism, where the combiner must keep all state in class members because the combiner's routines will be invoked for each signal called. Compare, for example, a combiner that returns the maximum element from calling the slots. If the maximum element ever exceeds 100, no more slots are to be called.</para> <informaltable> <tgroup cols="2" align="left"> <thead> <row> <entry><para>Pull</para></entry> <entry><para>Push</para></entry> </row> </thead> <tbody> <row> <entry> <programlisting> struct pull_max { typedef int result_type; template<typename InputIterator> result_type operator()(InputIterator first, InputIterator last) { if (first == last) throw std::runtime_error("Empty!"); int max_value = *first++; while(first != last && *first <= 100) { if (*first > max_value) max_value = *first; ++first; } return max_value; } }; </programlisting> </entry> <entry> <programlisting> struct push_max { typedef int result_type; push_max() : max_value(), got_first(false) {} // returns false when we want to stop bool operator()(int result) { if (result > 100) return false; if (!got_first) { got_first = true; max_value = result; return true; } if (result > max_value) max_value = result; return true; } int get_value() const { if (!got_first) throw std::runtime_error("Empty!"); return max_value; } private: int max_value; bool got_first; }; </programlisting> </entry> </row> </tbody> </tgroup> </informaltable> <para>There are several points to note in these examples. The "pull" version is a reusable function object that is based on an input iterator sequence with an integer <code>value_type</code>, and is very straightforward in design. The "push" model, on the other hand, relies on an interface specific to the caller and is not generally reusable. It also requires extra state values to determine, for instance, if any elements have been received. Though code quality and ease-of-use is generally subjective, the "pull" model is clearly shorter and more reusable and will often be construed as easier to write and understand, even outside the context of a signals & slots library.</para> <para> The cost of the "pull" combiner interface is paid in the implementation of the Signals library itself. To correctly handle slot disconnections during calls (e.g., when the dereference operator is invoked), one must construct the iterator to skip over disconnected slots. Additionally, the iterator must carry with it the set of arguments to pass to each slot (although a reference to a structure containing those arguments suffices), and must cache the result of calling the slot so that multiple dereferences don't result in multiple calls. This apparently requires a large degree of overhead, though if one considers the entire process of invoking slots one sees that the overhead is nearly equivalent to that in the "push" model, but we have inverted the control structures to make iteration and dereference complex (instead of making combiner state-finding complex).</para> </section> <section> <title>Connection Interfaces: += operator</title> <para> Boost.Signals supports a connection syntax with the form <code>sig.<methodname>connect</methodname>(slot)</code>, but a more terse syntax <code>sig += slot</code> has been suggested (and has been used by other signals & slots implementations). There are several reasons as to why this syntax has been rejected:</para> <itemizedlist> <listitem> <para><emphasis role="bold">It's unnecessary</emphasis>: the connection syntax supplied by Boost.Signals is no less powerful that that supplied by the <code>+=</code> operator. The savings in typing (<code>connect()</code> vs. <code>+=</code>) is essentially negligible. Furthermore, one could argue that calling <code>connect()</code> is more readable than an overload of <code>+=</code>.</para> </listitem> <listitem> <para><emphasis role="bold">Ambiguous return type</emphasis>: there is an ambiguity concerning the return value of the <code>+=</code> operation: should it be a reference to the signal itself, to enable <code>sig += slot1 += slot2</code>, or should it return a <code><classname>connection</classname></code> for the newly-created signal/slot connection?</para> </listitem> <listitem> <para><emphasis role="bold">Gateway to operators -=, +</emphasis>: when one has added a connection operator <code>+=</code>, it seems natural to have a disconnection operator <code>-=</code>. However, this presents problems when the library allows arbitrary function objects to implicitly become slots, because slots are no longer comparable. <!-- (see the discussion on this topic in User-level Connection Management). --></para> <para> The second obvious addition when one has <code>operator+=</code> would be to add a <code>+</code> operator that supports addition of multiple slots, followed by assignment to a signal. However, this would require implementing <code>+</code> such that it can accept any two function objects, which is technically infeasible.</para> </listitem> </itemizedlist> </section> <section> <title><code>trackable</code> rationale</title> <para> The <code><classname>trackable</classname></code> class is the primary user interface to automatic connection lifetime management, and its design affects users directly. Two issues stick out most: the odd copying behavior of <code>trackable</code>, and the limitation requiring users to derive from <code>trackable</code> to create types that can participate in automatic connection management.</para> <section> <title><code>trackable</code> copying behavior</title> <para> The copying behavior of <code><classname>trackable</classname></code> is essentially that <code><classname>trackable</classname></code> subobjects are never copied; instead, the copy operation is merely a no-op. To understand this, we look at the nature of a signal-slot connection and note that the connection is based on the entities that are being connected; when one of the entities is destroyed, the connection is destroyed. Therefore, when a <code><classname>trackable</classname></code> subobject is copied, we cannot copy the connections because the connections don't refer to the target entity - they refer to the source entity. This reason is dual to the reason signals are noncopyable: the slots connected to them are connected to that particular signal, not the data contained in the signal.</para> </section> <section> <title>Why derivation from <code>trackable</code>?</title> <para> For <code><classname>trackable</classname></code> to work properly, there are two constraints:</para> <itemizedlist> <listitem> <para><code><classname>trackable</classname></code> must have storage space to keep track of all connections made to this object.</para> </listitem> <listitem> <para><code><classname>trackable</classname></code> must be notified when the object is being destructed so that it can disconnect its connections.</para> </listitem> </itemizedlist> <para>Clearly, deriving from <code><classname>trackable</classname></code> meets these two guidelines. We have not yet found a superior solution.</para> </section> </section> <section> <title>Comparison with other Signal/Slot implementations</title> <section> <title>libsigc++</title> <para> <ulink url="http://libsigc.sourceforge.net">libsigc++</ulink> is a C++ signals & slots library that originally started as part of an initiative to wrap the C interfaces to <ulink url="http://www.gtk.org">GTK</ulink> libraries in C++, and has grown to be a separate library maintained by Karl Nelson. There are many similarities between libsigc++ and Boost.Signals, and indeed Boost.Signals was strongly influenced by Karl Nelson and libsigc++. A cursory inspection of each library will find a similar syntax for the construction of signals and in the use of connections and automatic connection lifetime management. There are some major differences in design that separate these libraries:</para> <itemizedlist> <listitem> <para><emphasis role="bold">Slot definitions</emphasis>: slots in libsigc++ are created using a set of primitives defined by the library. These primitives allow binding of objects (as part of the library), explicit adaptation from the argument and return types of the signal to the argument and return types of the slot (libsigc++ is, by default, more strict about types than Boost.Signals). A discussion of this approach with a comparison against the approach taken by Boost.Signals is given in Choice of Slot Definitions.</para> </listitem> <listitem> <para><emphasis role="bold">Combiner/Marshaller interface</emphasis>: the equivalent to Boost.Signals combiners in libsigc++ are the marshallers. Marshallers are similar to the "push" interface described in Combiner Interface, and a proper treatment of the topic is given there.</para> </listitem> </itemizedlist> </section> <section> <title>.NET delegates</title> <para> <ulink url="http://www.microsoft.com">Microsoft</ulink> has introduced the .NET Framework and an associated set of languages and language extensions, one of which is the delegate. Delegates are similar to signals and slots, but they are more limited than most C++ signals and slots implementations in that they:</para> <itemizedlist> <listitem> <para>Require exact type matches between a delegate and what it is calling.</para> </listitem> <listitem><para>Only return the result of the last target called, with no option for customization.</para></listitem> <listitem> <para>Must call a method with <code>this</code> already bound.</para> </listitem> </itemizedlist> </section> </section> </section> --- NEW FILE: tests.xml --- <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE testsuite PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <testsuite last-revision="$Date: 2007/03/05 19:54:28 $"> <run-test filename="dead_slot_test.cpp"> <lib>../../../libs/test/build/boost_test_exec_monitor</lib> <lib>../build/boost_signals</lib> <purpose> <para>Ensure that calling <methodname>connect</methodname> with a slot that has already been disconnected via deletion does not actually connect to the slot.</para> </purpose> </run-test> <run-test filename="deletion_test.cpp"> <lib>../../../libs/test/build/boost_test_exec_monitor</lib> <lib>../build/boost_signals</lib> <purpose> <para>Test deletion of slots.</para> </purpose> </run-test> <run-test filename="ordering_test.cpp"> <lib>../../../libs/test/build/boost_test_exec_monitor</lib> <lib>../build/boost_signals</lib> <purpose><para>Test slot group ordering.</para></purpose> </run-test> <run-test filename="signal_n_test.cpp"> <lib>../../../libs/test/build/boost_test_exec_monitor</lib> <lib>../build/boost_signals</lib> <purpose> <para>Basic test of signal/slot connections and invocation using the <classname>boost::signalN</classname> class templates.</para> </purpose> </run-test> <run-test filename="signal_test.cpp"> <lib>../../../libs/test/build/boost_test_exec_monitor</lib> <lib>../build/boost_signals</lib> <purpose> <para>Basic test of signal/slot connections and invocation using the <classname>boost::signal</classname> class template.</para> </purpose> <if-fails> <para>The <classname>boost::signal</classname> class template may not be usable on your compiler. However, the <classname>boost::signalN</classname> class templates may still be usable.</para> </if-fails> </run-test> <run-test filename="trackable_test.cpp"> <lib>../../../libs/test/build/boost_test_exec_monitor</lib> <lib>../build/boost_signals</lib> <purpose> <para>Test automatic lifetime management using <classname>boost::trackable</classname> objects.</para> </purpose> </run-test> </testsuite> --- NEW FILE: tutorial.xml --- <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE section PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <section last-revision="$Date: 2007/03/05 19:54:28 $" id="signals.tutorial"> <title>Tutorial</title> <using-namespace name="boost"/> <using-namespace name="boost::signals"/> <using-class name="boost::signalN"/> <using-class name="boost::slotN"/> <section> <title>How to Read this Tutorial</title> <para>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 <emphasis>Beginner</emphasis>, [...1090 lines suppressed...] TextView v1(doc); HexView v2(doc); doc.append(argc == 2 ? argv[1] : "Hello world!"); return 0; }</programlisting> <para>The complete example source, contributed by Keith MacDonald, is available in <ulink url="../../libs/signals/example/doc_view.cpp"><code>libs/signals/example/doc_view.cpp</code></ulink>.</para> </section> <section> <title>Linking against the Signals library</title> <para>The thread_safe_signals version of Boost.Signals is currently a header-only library. No linking is to a compiled binary library is required. </para> </section> </section> --- NEW FILE: design.xml --- <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE section PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <section last-revision="$Date: 2007/03/05 19:54:28 $"> <title>Design Overview</title> <using-namespace name="boost"/> <using-namespace name="boost::signals"/> <section> <title>Type Erasure</title> <para>"Type erasure", where static type information is eliminated by the use of dynamically dispatched interfaces, is used extensively within the Boost.Signals library to reduce the amount of code generated by template instantiation. Each signal must manage a list of slots and their associated connections, along with a <code>std::map</code> to map from group identifiers to their associated connections. However, instantiating this map for every token type, and perhaps within each translation unit (for some popular template instantiation strategies) increase compile time overhead and space overhead.</para> <para> To combat this so-called "template bloat", we use Boost.Function and Boost.Any to store unknown types and operations. Then, all of the code for handling the list of slots and the mapping from slot identifiers to connections is factored into the class <code><classname>signal_base</classname></code> that deals exclusively with the <code>any</code> and <code><classname>function</classname></code> objects, hiding the actual implementations using the well-known pimpl idiom. The actual <code><classname>signalN</classname></code> class templates deal only with code that will change depending on the number of arguments or which is inherently template-dependent (such as connection).</para> </section> <section> <title><code>connection</code> class</title> <para> The <code><classname>connection</classname></code> class is central to the behavior of the Boost.Signals library. It is the only entity within the Boost.Signals system that has knowledge of all objects that are associated by a given connection. To be specific, the <code><classname>connection</classname></code> cla... [truncated message content] |