我看过一些关于线程的教程,但有一个问题让我很好奇。
std::thread Child([](){ std::cout << "When am I executed?" << std::endl << std::endl; });
//Some other code
Child.join();
//I'm guessing now my thread would be running
当我调用
join()
时,线程是否正在执行?它是在创建线程和调用join之间的某个时间运行吗?如果它在调用join()
时被执行,为了检查我的理解,它会告诉那一部分去执行并且你的程序继续在主线程上运行,最终子线程在使用与主线程相同的内存上完成了一些工作吗?如果我想为一个通用类创建一个包装器,我想做以下操作,但我似乎无法完全弄清楚。在管理线程方面,我感到困惑。
class Sync {
private:
int val;
public:
Sync() : val(0) {}
void Inc() {val++}
int Value() { return val; }
};
class Async {
private:
Sync Foo;
std::mutex mtx;
std::vector<std::thread*> Children;
public:
//I would need a new thread each time I called Inc
void Inc() {
Children.push_back(new std::thread([&]() {
mtx.lock();
Foo.Inc();
mtx.unlock();
}));
}
//But how do I know when it is safe to delete Child?
int Value() {
for(auto& thds : Children) {
thds->join();
delete thds;
}
Children.clear();
return Foo.Value(); }
};
我在考虑一个合适的位置,可能是在线程函数的结尾处,因为Child将不再需要,但如果您尝试从线程内部销毁线程会发生什么呢?我猜这听起来就像一个坏主意一样。如何知道何时可以删除我的线程?有更好的方法吗?
修改上述代码以反映下面的建议。
我现在意识到教程中所说的关于抛出异常的内容,所以我应该使用互斥锁保护而不是mtx.lock()。