Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I dont know why my simple c++ timer class does not work

I wrote a timer class, but it does not work the way I needed it to. Can anyone tell me what is wrong with this?

template<typename D, typename C>
class timer
{
public:
    timer(D period, C&& callback)
    {
        std::thread t{[&](){
            std::this_thread::sleep_for(period);
            callback();
        }};

        t.detach();
    }
};

int main()
{
    timer t1(std::chrono::seconds(2), [](){
        std::cout << "hello from 1\n";
    });

    timer t2(std::chrono::seconds(3), [](){
        std::cout << "hello from 2\n";
    });

    std::this_thread::sleep_for(std::chrono::seconds(5));
}

The output is only:

hello from 1

Where is the ‘hello from 2’ line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here:

timer(D period, C&& callback)
{
    std::thread t{[&](){
        std::this_thread::sleep_for(period);
        callback();
    }};

    t.detach();
}

period and callback are destructing as timer returns, and timer returns way before callback() is called, and possibly even before sleep_for is called.

The fix is to copy period and callback into the thread’s functor so that those copies are still alive while the thread runs:

timer(D period, C&& callback)
{
    std::thread t{[=](){
        std::this_thread::sleep_for(period);
        callback();
    }};

    t.detach();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading