timercpp
timercpp copied to clipboard
it's not thread safe
to reproduce
for(int i=1;i<100;i++)
std::thread(test1).detach();
void test1()
{
Timer t = Timer();
t.setInterval([&](){
},
1000);
t.stop();
}
results Exception has occurred. Segmentation fault
yes, I think active variable is useless
Because the Timer is destroyed after t.stop(), and the thread inside the setInterval function uses the Timer after the destruction.
An idea: Timer inherits std::enable_shared_from_this to extend the life cycle of Timer until the thread inside setInterval function ends.
Modified code:
timerrcpp.h
test program:
test.cpp