I have gone through similar questions on Stackoverflow but still can't get a good answer:
I am quite puzzled on how this signal/slot is achieved.
Q1: From the following code, sig is connected to two function(Hello() and World()), and it seems that the functions are called in a serialized manner, which also implies that, one function(Hello()) need to be completed before going into another function(World())? => Single thread program
Q2: Are there anyway to enable multi-threaded signal/slot?(=> World() will start instantly, don't need to wait for Hello() to complete.) Or if it's not recommended, would you mind tell me why?
Sample codes on Boost website:
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();
Output: Hello, World!
Q1:
The calls are serialized. What signals are doing internally is, greatly simplified:
foreach connection:
call handler
Therefore you don't want to block in the handlers for long. If you need to do much work you can invoke it from there though, for example by creating a thread for it.
Q2:
boost signals 1 isn't even thread-safe; signals 2 is, but still does serialized calls. As signals are mostly used for event handling it is common style to not actually do much work in the handlers.
Thus there is no real benefit in calling them 'in parallel', the benefits would not in general justify the overhead of the neccessary thread invocations.
Q1: you are correct. Fixed my answer to the question you referenced to reflect that.
Q2: it seems you're confused by what should be threaded. In emitting/capturing process what contains code is the slot. So if you want to run the code concurrently, you should place the slots in different threads.
Such behavior is supported by Qt (don't know about boost, actually), and there's a chapter in qt manual that explains, that you most likely need "queued processing" for such behavior. But then you'll have to have the notion of "event loop" in the thread that executes the slot code (because you can't just tell the working thread "hey, stop doing your stuff, do this instead!").
If you don't want to wait, you'll have to spawn threads in slot codes directly. And you should not forget to use some kind of "wait" function in the code both slots have access to. By the way, both boost and Qt have nice wrappers around system threading libraries to do it easilly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With