【发布时间】:2019-02-28 15:51:10
【问题描述】:
我有一个非常简单的 C++ 程序,如下所示。 A、B 和 C 类位于 DLL 中。当我关闭此应用程序时,它有时会在条件变量上调用 notify_all() 时崩溃。谁能告诉我原因?
我已经检查了很多关于 SO 的 Q/A,但没有一个能解决我的问题。我在 Windows 7 和 VS2013 上工作。
class B;
class C
{
public:
C(const std::weak_ptr<B>& b) : mB(b)
{
}
virtual ~C()
{
}
void run()
{
while (true)
{
std::unique_lock<std::mutex> uLock(mMutex);
// Wait until some event is happening
mCondition.wait_for(uLock, std::chrono::seconds(300));
if (!mStop)
{
//do something here
}
else
{
return;
}
}
}
void start()
{
mThread = std::thread(&C::run, this);
}
void stop()
{
mStop = false;
}
void notify()
{
mCondition.notify_all();
}
void join()
{
if (mThread.joinable())
{
mThread.join();
}
}
private:
std::atomic<bool> mStop;
std::condition_variable mCondition;
std::mutex mMutex;
std::thread mThread;
std::weak_ptr<B> mB;
};
class B : public std::enable_shared_from_this<B>
{
public:
B() {}
~B()
{
if (mC)
{
mC->stop();
mC->notify();
mC->join();
}
}
// basic methods
void init()
{
mC = std::unique_ptr<C>(new C(shared_from_this()));
mC->start();
}
private:
std::unique_ptr<C> mC;
};
class A
{
public:
~A(){}
void init() { pImpl->init(); }
static std::shared_ptr<A> getInstance(){
static std::shared_ptr<A> instance(new A);
return instance;
}
private:
A() : pImpl(std::make_shared<B>()){}
std::shared_ptr<B> pImpl;
};
void main()
{
std::shared_ptr<A> a = A::getInstance();
a->init();
int x;
std::cin >> x;
}
编辑 1: 如果我将 B 的析构函数中的代码放在不同的函数中(例如 clean())并从 main() 调用它(在 A 中使用 clean() 方法)不会崩溃正在发生。
【问题讨论】:
标签: c++ multithreading c++11 condition-variable