Repository navigation
TutorialIntermediate
Dmitry Koplyarov edited this page Feb 10, 2016
·
14 revisions
- Connecting from another thread
- Guarding an external state with a signal mutex
- The external state and the populators
class Timer
{
std::atomic<bool> _alive;
std::thread _thread;
public:
wigwag::signal<void()> OnTick;
Timer()
: _alive(true), _thread(&Timer::ThreadFunc, this)
{ }
~Timer()
{
_alive = false;
_thread.join();
}
private:
void ThreadFunc()
{
while (_alive)
{
std::this_thread::sleep(std::chrono::seconds(1));
OnTick();
}
}
};
// ...
{
Timer timer;
wigwag::token t = timer.OnTick.connect([] { std::cout << "tick" << std::endl; });
std::this_thread::sleep(std::chrono::milliseconds(3500));
}Output:
tick
tick
tick
Using the default specialization of singal template class is thread-safe while you have no external state.
class Timer
{
std::atomic<bool> _alive;
int _tickCount;
std::thread _thread;
public:
wigwag::signal<void(int)> OnTick;
Timer()
: _alive(true), _thread(&Timer::ThreadFunc, this)
{ }
~Timer()
{
_alive = false;
_thread.join();
}
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);
}
}
};
// ...
{
Timer 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