Programmer
Programmer

Reputation: 8687

Thread how to change sleep time

In my project I have function as defined below:

void start(std::chrono::milliseconds delay) override
{
    mDelay = delay;
    if(mThread == nullptr)
    {
        mThread = std::make_unique<Thread>([&]()
        {
            sleep(std::chrono::milliseconds(mDelay));
        });
    }
}

When I call the method for first time the thread is created and goes to sleep for mDelay period. But I need to change the mDelay time again but for a lesser time period than the earlier one supplied.

But when I call it again I am unable to cancel the previous sleep and start a new one with defined mDelay?

How can I achieve the same?

Upvotes: 1

Views: 284

Answers (3)

JVApen
JVApen

Reputation: 11317

I see what you are trying to do, I believe std::condition_variable is what you are searching for.

Instead of sleep, you can call wait_for. When you want to wake the thread, you can call notify_one.

Upvotes: 2

ObliteratedJillo
ObliteratedJillo

Reputation: 5156

Move and dispose old thread ( from mobile, code not tested). If the thread were to trigger a handler, just raise a killed flag so that the disposed thread will not triggered once killed.

 if(mThread != nullptr)
 {
     auto dispose = std::move(mThread);
     dispose->detach();
     mThread.reset(new Thread([&]()
    {
        sleep(std::chrono::milliseconds(mDelay));
    });
  }

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 595402

Once the thread has been created for the first time, mThread is never reset after the thread finishes its work. The next time start() is called, mThread is not nullptr anymore, and thus a new thread is not created with the updated delay.

Either the Thread lambda needs to reset mThread to nullptr before exiting, or else Thread needs a bool member that the lambda can set before exiting. Either way will allow start() to know when a new thread is needed.

Upvotes: 1

Related Questions