【发布时间】:2016-03-02 09:17:31
【问题描述】:
我有一个对象,其中包含一个间接访问该对象的线程,如下所示:
#include <iostream>
#include <thread>
#include <atomic>
class A;
class Manager
{
public:
Manager(void) = default;
void StartA(void)
{
a = std::make_unique<A>(*this);
}
void StopA(void)
{
a = nullptr;
}
A& GetA(void)
{
return *a;
}
private:
std::unique_ptr<A> a;
};
class A
{
public:
A(Manager& manager)
: manager{manager},
shouldwork{true},
thread{[&]{ this->Run(); }}
{
}
~A(void)
{
shouldwork = false;
thread.join();
}
private:
Manager& manager;
std::atomic<bool> shouldwork;
std::thread thread;
void Run(void)
{
while (shouldwork)
{
// Here goes a lot of code which calls manager.GetA().
auto& a = manager.GetA();
}
}
};
int main(int argc, char* argv[])
try
{
Manager man;
man.StartA();
man.StopA();
}
catch (std::exception& e)
{
std::cerr << "Exception caught: " << e.what() << '\n';
}
catch (...)
{
std::cerr << "Unknown exception.\n";
}
问题是当一个线程调用Manager::StopA并进入A的析构函数时,A内部的线程在Manager::GetA处发生段错误。我该如何解决这个问题?
【问题讨论】:
-
您将遇到分段错误,因为您尝试取消引用
nullptr。调用 StopA 会将a设置为nullptr。 GetA 取消引用它return *a
标签: c++ multithreading c++11 c++14