timercpp icon indicating copy to clipboard operation
timercpp copied to clipboard

it's not thread safe

Open Igor-Mochalin opened this issue 4 years ago • 2 comments

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

Igor-Mochalin avatar Mar 06 '22 17:03 Igor-Mochalin

yes, I think active variable is useless

ckt1010 avatar Mar 14 '22 13:03 ckt1010

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

lilucpp avatar Jan 19 '23 07:01 lilucpp