Repository navigation
TutorialIntermediate
- Connecting from another thread
- Guarding an external state with a signal mutex
- The external state and the populators
- Async handlers and task_executors
- Listenable and listeners
- Signal connectors
- Signal and handler attributes
The default specialization of signal template is thread-safe.
You may invoke a signal and connect to it from different threads without any problems if you have no external state to guard.
class StupidTimer
{
std::atomic<bool> _alive;
std::thread _thread;
public:
StupidTimer()
: _alive(true)
{
_thread = std::thread(&StupidTimer::ThreadFunc, this);
}
~StupidTimer()
{
_alive = false;
_thread.join();
}
wigwag::signal<void()> OnTick;
private:
void ThreadFunc()
{
while (_alive)
{
std::this_thread::sleep(std::chrono::seconds(1));
OnTick();
}
}
};
// ...
{
StupidTimer timer;
wigwag::token t = timer.OnTick.connect([] { std::cout << "tick" << std::endl; });
std::this_thread::sleep(std::chrono::milliseconds(3500));
}Output:
tick
tick
tick
However, usually you do have a state associated with a signal. In such a case, if you want to modify the state and invoke the signal atomically, you should use the signal::lock_primitive() getter.
In this sample code, the signal internal mutex is locked when the associated state is modified and the signal is invoked and also when the associated state is obtained.
class StupidTimer
{
std::atomic<bool> _alive;
int _tickCount;
std::thread _thread;
public:
StupidTimer()
: _alive(true)
{
_thread = std::thread(&StupidTimer::ThreadFunc, this);
}
~StupidTimer()
{
_alive = false;
_thread.join();
}
wigwag::signal<void(int)> OnTick;
int GetTickCount() const
{
std::lock_guard<std::recursive_mutex> l(OnTick.lock_primitive());
return _tickCount;
}
private:
void ThreadFunc()
{
while (_alive)
{
std::this_thread::sleep(std::chrono::seconds(1));
std::lock_guard<std::recursive_mutex> l(OnTick.lock_primitive());
++_tickCount;
OnTick(_tickCount);
}
}
};
// ...
{
StupidTimer timer;
std::cout << "ticks before connect: " << timer.GetTickCount() << std::end;
wigwag::token t = timer.OnTick.connect([] (int n) { std::cout << "tick " << n << std::endl; });
std::this_thread::sleep(std::chrono::milliseconds(3500));
}Output:
ticks before connect: 0
tick 1
tick 2
tick 3
The previous code snippet has an important design flaw:
- There is a race condition between connecting to a signal and obtaining the initial object state. You have to lock the mutex in the code that connects a handler to get rid of that race condition.
{
StupidTimer timer;
std::unique_lock<std::recursive_mutex> l(timer.OnTick.lock_primitive());
std::cout << "ticks before connect: " << timer.GetTickCount() << std::end;
wigwag::token t = timer.OnTick.connect([] (int n) { std::cout << "tick " << n << std::endl; });
l.unlock();
std::this_thread::sleep(std::chrono::milliseconds(3500));
}Luckily, the wigwag library has a better solution for this problem: the populators.
A populator is a user-defined function that is invoked when a handler is connected to a signal. The handler is passed to this function, and the function should invoke it to populate the associated state.
The signal mutex is locked while connecting to a signal and populating the state, so there is no more race condition there.
For a single-object state, this function would just pass the state to the handler:
void OnStateChangedPopulator(const std::function<void(State)>& handler) const
{
handler(_state);
}For a container state, this function would invoke the handler multiple times, as if all the elements were added right at the moment of connecting:
void OnContainerChangedPopulator(const std::function<void(ContainerOp, ElementType)>& handler) const
{
for (const auto& e : _container)
handler(ContainerOp_ItemAdded, e);
}So, here's the StupidTimer code with a populator:
class StupidTimer
{
std::atomic<bool> _alive;
int _tickCount;
std::thread _thread;
public:
StupidTimer()
: _alive(true),
OnTick(std::bind(&StupidTimer::OnTickPopulator, this, std::placeholders::_1))
{
_thread = std::thread(&StupidTimer::ThreadFunc, this);
}
~StupidTimer()
{
_alive = false;
_thread.join();
}
wigwag::signal<void(int)> OnTick;
private:
// This function is invoked when a handler is being connected to a signal
void OnTickPopulator(const std::function<void(int)>& handler) const
{
// The signal mutex is already locked here!
handler(_tickCount);
}
void ThreadFunc()
{
while (_alive)
{
std::this_thread::sleep(std::chrono::seconds(1));
std::lock_guard<std::recursive_mutex> l(OnTick.lock_primitive());
++_tickCount;
OnTick(_tickCount);
}
}
};
// ...
{
StupidTimer timer;
wigwag::token t = timer.OnTick.connect([] (int n) { std::cout << "tick " << n << std::endl; });
std::this_thread::sleep(std::chrono::milliseconds(3500));
}Output:
tick 0
tick 1
tick 2
tick 3
If you want shorter code, you may use a labmda function as a populator:
StupidTimer()
: _alive(true), OnTick([&](const std::function<void(int)>& h) { h(_tick); })
{
_thread = std::thread(&StupidTimer::ThreadFunc, this);
}
Or a lambda function with an auto argument type if you use C++14:
StupidTimer()
: _alive(true), OnTick([&](auto&& h) { h(_tick); })
{
_thread = std::thread(&StupidTimer::ThreadFunc, this);
}Please note: populators are about connecting to a signal, not invoking it, so you still have to lock the mutex when you modify the associated state and invoke a signal!
Sometimes you want signal handler to be executed not in the same thread where the signal is invoked. A good example is a UI component connecting to some core subsystem.
To connect an asynchronous handler, you should use signal::connect method with a task_executor parameter:
class MediaScannerStateLabel : public UiLabel
{
private:
wigwag::token _token;
public:
MediaScannerStateLabel(const std::shared_ptr<wigwag::task_executor>& uiThread, const MediaScannerPtr& scanner)
{ _token = scanner->OnStateChanged.connect(uiThread, [&](MediaScannerState s) { this->StateChangedHandler(s); }); }
~MediaScannerStateLabel()
{ _token.reset(); }
private:
void StateChangedHandler(MediaScannerState s)
{
switch (s)
{
case MediaScannerState::Scanning:
SetText("Scanning...");
break;
case MediaScannerState::Idle:
default:
SetText("");
break;
}
}
};Here, when a MediaScanner invokes the OnStateChanged signal from its own thread, the MediaScannerStateLabel::StateChangedHandler is executed in the uiThread task_executor.
task_executor is an abstract class. You may use thread_task_executor and threadless_task_executor subclasses from the wigwag library, or implement your own (e.g. a wrapper for a similar entity in you project).