Signals library which tracks slots lifetime automatically - c++

I need a signals/slots c++ library with one specific feature that the signals automatically disconnect the slot when the object with the slot is destroyed.
Boost::signals2 offers this feature only for object created with boost::shared_ptr and I want to keep using std::shared_ptr everywhere. There is an option to make it work with std::shared_ptr but it requires writing some specialized templates and there is no info how it should like and generally I'd prefer to avoid it (unless there is the code somewhere in the internet, but I couldn't find it).
I know that Qt signals have this feature, but well Qt is too big to use it in every project.

According to Boost documentation (checked in 1.48.0), the necessary template specialisations for std::shared_ptr and std::weak_ptr already exist in Boost, so std smart pointers should be usable out of the box with signals2 (via slot::track_foreign).

I'd suggest taking a look at the sigslot library -- http://sigslot.sourceforge.net
It's a simple mechanism that doesn't require a preprocessor (like Qt's signals) and provides automatic disconnection of deleted slots.

Related

Only plain pointers used in Qt API

I've been working with Qt for somedays and I wonder why all their API uses plain pointers instead of their own smart pointers like QSharedPointer.
Wouldn't it be more consistent to use them?
QSharedPointer is implemented since Qt 4.5. In Qt, QObjects organize themselves in object trees. When you create a QObject, with another object as the parent, the former is added to the latter's children list and destroyed in the latter's destructor. So you do not need to use QSharedPointer with its overhead.
Why should QSharedPointer be used when in Qt APIs object ownership is usually exclusive to one object? There is no need for sharing.
A more appropriate question would be why is Qt using raw pointers instead of smart pointers (be those Qt's or C++11's), and the reason for this is simple - those are new features, and even though Qt 5 has been released after C++11 (and internally employs it), rewriting everything to use smart pointers besides tedious will also result in annihilation of backward comparability of user code.
Overall, Qt APIs seem to be somewhat lacking and incoherent in this regard. For example - it is a major inconvenience that Qt's smart pointers are not supported in QtQuick, which uses its own private smart pointer implementation, so you should either have ownership managed by the QML engine or by C++, but you cannot really share across the two.

Using futures with boost::asio

Does anyone have a good pointer to examples which use futures from the Boost thread library with Boost ASIO? I have an existing asynchronous library which uses callback function that I would like to provide a friendlier synchronous interface for.
It is difficult to provide a concise solution without understanding the interactions with the existing asynchronous library. Nevertheless, this answer uses Boost.Future and Boost.Asio to implement an Active Object pattern. When creating a future, consider examining the existing asynchronous library to determine which approach is more appropriate:
boost::packaged_task provides a functor that can create a future. This functor can be executed within the context of Boost.Asio io_service. Some additional level of wrapping may be required to integrate with the existing asynchronous library, as well as work around rvalue semantics. Consider using this approach if the current function calls already return the value.
boost::promise provides a lower level object which can have its value set. It may require modifying existing functions need to accept the promise as an argument, and populate it within the function. The promise would be bound to the handler that is provided to Boost.Asio io_service. As with boost::packaged_task, it may require an additional level of wrapping to deal with rvalue semantics.
Finally, Boost.Asio 1.54 (currently in beta), provides first-class support for C++ futures. Here is the official example. Even if you are unable to currently use 1.54 beta, it may be beneficial to examine the interface and implementation.
Can you please look at this example:
http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp11/futures/daytime_client.cpp
It shows how to use std::future with boost asio.
The key point is to include file use_future.hpp:
#include <boost/asio/use_future.hpp>
Then you can write code like that:
std::future<std::size_t> my_future =
my_socket.async_read_some(my_buffer, boost::asio::use_future);
If you need to use boost::future then I'd suggest to implement another variant, similar to boost::asio::use_future.
The file use_future.hpp is a good example for that.

Is there a common design pattern or object oriented approach used to encapsulate thread behaviour?

I have recently been using pthreads on Linux and want to start looking into using boost threads in the near future. I have never used MS visual studio so I don't know the approach there but I (have to) use Embarcadero C++ Builder (formerly Borland) one of the few good things I find with it is that is has a built in class TThread. This is a class that you can derive from to give nicely encapsulated data and start and terminate functions. I prefer this approach than the pthread way of passing functions and void* being passed into the thread create function. I was wondering if there is some kind of design pattern or structure that is commonly used to provide a more object oriented that encapsulates the functionality of threads in this way? I can try and create it myself, but I cannot be the first person to desire this kind of approach and wondered if there was a "standard" way of achieving it.
Edit: Alternatively, if this is a very bad idea perhaps an illustration of why?
I would consider that the most standard approach would be using the standard thread library (closely related to boost::thread, not 100% the same). I would avoid redesigning what has already been designed, reviewed and verified by a committee of experts.
Also note that for the kind of operations that you mention in the comment you might want to take a look at the future part of the standard library (again similar to the boost counterpart), and in particular to the std::asynch function.
I like the way boost::thread is designed (I saw a similar design in the threading library from Rouge Wave). Basically a thread is started by passing a function to be executed and latter that thread object can be used to join that thread. pthread is very similar in design, but boost::thread is much easier to use.

How to dynamically load C++ objects and use them through a wrapper interface

I have a multithreaded dynamic library which exposes a basic API and which I use in a
couple of applications. Currently I'm using a custom(as in legacy) implementation of some basic threading and synchronization primitives with which I'm not happy at all as it does not provide much flexibility, features and it's also a hassle to maintain(has implementations for both Linux and Windows).
I would like to replace that with some existing threading library but I would also like to provide some flexibility, meaning that I would like to be able to try out a bunch of libraries to see how they perform on different platforms I build my library for(I would like to try boost::thread, Poco::Thread and the new C++0X thread implementation) or even let the user to which I provide my library to fit it's own thread custom implementation if wanted, so that the library and the user's app would be able to use the same threading infrastructure - ideally I would have a config file or something on those lines to let the user specify its desired implementation or use a default provided one.
I was thinking of the following:
making a thin wrapper(pimpl style) to be used inside my library that will use a dynamic class loader to fit the desired implementation at runtime. But how could I handle the case of the C++0X threads? These are in the standard library which will already be linked against my library so no point in custom loading it at runtime.
using a dynamic loader coupled with the Prototype design pattern. But the pattern requires the implementation of the clone() method which would mean changing the threading library code. I might have poorly understood the pattern and I might be mistaking about this, so please correct me if I'm wrong.
As you can see I don't have many ideas to work with right now(but it's a start) so any pointers on the following would be of great help:
Is providing such a functionality a good idea? Do you see any caveats?
Is the dynamic loading facility a feasible idea? What are the downsides?
Any pointers/links on how to properly implement that?
If I'm going the "thin wrapper" way would it be a good idea to expose it as part of my library's API?
Are there any alternatives/patterns to achieve the same kind of functionality(I mean to achieve the same result but without dynamic loading)?
What is the benefit of providing the ability to dynamically or delay load of a threading solution? Ideally you would pick a threading solution and create a library which has an API interface and if the solution was later found to be insufficient you could write a new library using the same interface but a different underlying solution. I would even consider statically linking such a library although a DLL is fine as well. I wouldn't bother with the ability to make it interchangeable at runtime or anything like that.
I highly recommend Boost threads. Cross platform and based off POSIX it's very easy to implement in a variety of ways. I believe that C++0x threads were marginally based off this solution however since C++0x is not finalized or fully supported by all compilers yet I would only consider it as a replacement for boost in the future.
I think that by providing a wrapper for the threading library, and initializing it at runtime, you are limiting yourself to the lowest common denominator. That is, your interface into the thread library calls will need to include operations that are implemented by all of the libraries.
If this is acceptable, then you should look into using the Adapter Pattern to handle calls into the thread library that is chosen by the user. Basically, you would use the config file to determine which thread library is in use, and then wrap it in an adapter class that implements your threading operations methods interface and delegates the calls the appropriate methods on the underlying library. You could also use the adapter to make up for unimplemented functionality in certain library (i.e. by implementing reader/writer locks using the mutexes provided by a library, etc.)

How do you implement Signals and Events in C++?

I am making a Gui Library on top of SDL using C++. (Don't ask me why, I am just doing it to gain some knowledge out of practice in order to understand how Gui libraries are made.) And I want to make a signal connection system like gtk+ or wxWidgets...
g_signal_connect(mybutton,"clicked",gtk_main_quit); //Gtk+
EVT_MENU(wxID_EXIT,OnQuit); //WxWidgets
I understand I can do this using function pointers. But how do I add the functions to the main loop?
Or Is there a better way to do this?
The simplest way is borrowing it from a library, for example boost::signal or boost::signal2. The next best thing is implementing your own but borrowing most of the features from libraries like boost::bind (to enable the connections) or using C++0x features that will simplify the generic connection of clients (std::function / boost::function).
I would recommend that you use boost and their signals2 library, as there are many things that you can do wrong and are already solved there.