下面我提供了我遇到的情况的伪代码。我有两个资源需要在一个线程上创建,另一个需要在主线程上创建。但是,第一个资源ResourceA必须在创建ResourceB之后重新创建,但ResourceA必须在创建ResourceB之前“准备好”(如果您对更多详细信息感兴趣,请参阅注释部分。)
我的确切问题是:
有问题的课程将被定义为:
class Foo : public non_copyable // You can still move
{
private:
struct FooImpl;
FooImpl *m_foo;
void Run();
public:
Foo();
~Foo();
bool Init();
};
在Foo.cpp内部,我们有以下定义:
struct Foo::FooImpl
{
ResourceA ra;
ResourceB rb;
};
Foo::Foo() :
m_foo(new FooImpl())
{}
Foo::~Foo()
{
delete m_foo;
}
void Foo::Run()
{
[Create Resource B in an advanced state needed to recreate A]
[Notify condition on main thread so Resource B can be recreated]
[Conditionally wait for A to be recreated on main thread]
[Do stuff with B and this]
}
bool Foo::Init()
{
[Create Resource A in Preparation for Resource B this must be done on this thread]
std::thread t(std::bind(&Foo::Run, this)); // Note here I am not passing
// by std::ref. This is the line in
// question
[Conditionally wait for Resource B to be created on thread t]
[Recreate Resource A now that B has been created]
[Notify condition on thread t that A has been recreated]
[Handle A stuff and do stuff with this]
}