等待条件变量的 class 销毁
Destruction of class with condition variable in wait
我的问题如下:
我有一个等待条件变量的线程。我需要销毁这个线程。看起来很简单:
~myclass()
{
myConditionVariable.notifyAll();
myThread.join();
}
但是这样做的问题是,线程 运行 析构函数可能会停止,从而允许对条件变量进行新的等待调用。
最重要的是,我有一个成员函数,其中包含对条件变量的等待调用。说:
myMemberFunction()
{
myConditionVariable.wait(myLock);
}
这可能会在多个线程上从外部调用。我如何确保所有这些调用在实际销毁之前结束。
编辑:
为完成样本 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?
}
};
假设我们是从主线程(称为线程A)调用~myclass
,您可以检查是否需要在从线程(称为线程B)中停止:
我们有一个名为 Stop
的 Atomic<bool>
变量,可以从两个线程访问它。
在线程A中:
~myclass()
{
Stop = true;
myConditionVariable.notifyAll();
myThread.join();
}
在线程B中:
myConditionVariable.wait(myMutexLock, [&] return Stop || haveWorkToDo(); );
if (Stop)
// Terminate Thread
// continue to work
我的问题如下:
我有一个等待条件变量的线程。我需要销毁这个线程。看起来很简单:
~myclass()
{
myConditionVariable.notifyAll();
myThread.join();
}
但是这样做的问题是,线程 运行 析构函数可能会停止,从而允许对条件变量进行新的等待调用。
最重要的是,我有一个成员函数,其中包含对条件变量的等待调用。说:
myMemberFunction()
{
myConditionVariable.wait(myLock);
}
这可能会在多个线程上从外部调用。我如何确保所有这些调用在实际销毁之前结束。
编辑:
为完成样本 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?
}
};
假设我们是从主线程(称为线程A)调用~myclass
,您可以检查是否需要在从线程(称为线程B)中停止:
我们有一个名为 Stop
的 Atomic<bool>
变量,可以从两个线程访问它。
在线程A中:
~myclass()
{
Stop = true;
myConditionVariable.notifyAll();
myThread.join();
}
在线程B中:
myConditionVariable.wait(myMutexLock, [&] return Stop || haveWorkToDo(); );
if (Stop)
// Terminate Thread
// continue to work