Destroying a class with a pending condition variable

My problem is this:

I have a thread waiting for a condition variable. And I need to destroy this thread. It looks simple enough:

~myclass()
{
    myConditionVariable.notifyAll();
    myThread.join();
}

      

However, the problem is that the thread executing the destructor can be stopped, allowing new wait calls for the condition variable.

At the top, I have a member function with a wait call on a condition variable. Say:

myMemberFunction()
{
    myConditionVariable.wait(myLock);
}

      

It can be caused externally by multiple threads. How to make sure all these calls are wrapped before the actual destruction.

Edit:

To complete the sample class:

Myclass()
{
public:
    std::mutex waitMutex;

    std::condition_variable waitConditionVariable;

    //n.b. this function can be called from multiple threads;
    void wait()
    {
        std::condition_variable(wait);
    }

    ~MyClass()
    {
         //what should i do here?
    }

};

      

+3


source to share


1 answer


Suppose we are calling ~myclass

from the main thread (call it Thread A), you can check if it needs to be stopped in the slave thread (call it Thread B):

And we have a Atomic<bool>

named variable Stop

accessible from both threads.

On stream A:



~myclass()
{
    Stop = true;   
    myConditionVariable.notifyAll();
    myThread.join();
}

      

On stream B:

myConditionVariable.wait(myMutexLock, [&] return Stop || haveWorkToDo(); );
if (Stop)
   // Terminate Thread
// continue to work

      

+1


source







All Articles