0

I have a singleton class which looks something like:

//Test.h
class Test
{
private:
    static std::mutex mtx;
    static std::condition_variable cv;
    static bool end;

    static void DoSomethingThread();
    static void SomeOtherFunction();
public:
    static void Start();
}

//Test.cpp
std::mutex Test::mtx;
std::condition_variable Test::cv;
bool Test::end = false;

void Test::Start() 
{
    std::thread t_thread(Test::DoSomethingThread);

    while(a) {
        if (b) {
            // End thread.
            std::unique_lock<std::mutex> lock(mtx);
            Test::end = true;
            Test::cv.notify_one();
            t_thread.join();

            Test::SomeOtherFunction();

            // Restart thread.
            Test::end = false;
            t_thread = std::thread(Test::DoSomethingThread);
        }

        ...
    }
}

void Test::DoSomethingThread()
{
    std::unique_lock<std::mutex> lock(mtx);

    while (1) {
        //Do some work here.

        Test::cv.wait_for(lock, std::chrono::seconds(1000), []() { return Test::end; });

        if (Test::end) { break; }
    }
}

I found this code on this page and to be honest dont really know how this works. But the guy had the same problem as me and I thought it would work for my case to, but it didnt.

So what I currently have is have a thread t_thread which runs forever, it does some work and then sleeps for 1000 seconds and all over again. What I need is some way to wake this thread up from sleep and exit it. So SomeOtherFunction() can do its work and then restart the thread.

Why doesnt this code works, and how can I make it work?

user1806687
  • 934
  • 1
  • 10
  • 27

1 Answers1

1

I went back to original post and did:

if (b) {
    {       
        // End thread.
        std::unique_lock<std::mutex> lock(mtx);
        Test::end = true;
        Test::cv.notify_one();
    }   

    t_thread.join();

    Test::SomeOtherFunction();

    // Restart thread.
    Test::end = false;
    t_thread = std::thread(Test::DoSomethingThread);
}

And it works now. Thanks anyway.

user1806687
  • 934
  • 1
  • 10
  • 27