假设我有一个仿函数 F
struct F
{
// <some member variables go here>
void operator()() { while(true) /*do stuff affecting the state*/; }
};
如果我创建一个 Fs vector
std::vector<F> functorVec(10);
然后用这些仿函数启动一堆线程
for (int i = 0; i < functorVec.size(); ++i)
{
boost::thread(functorVec[i]);
}
现在我对我的 vector 做了一些事情,比如
functorVec.push_back(F());
如果 vector 扩展并将其内容复制到新位置,这是否会导致线程中出现未定义的行为?还是他们会崩溃?
好像他们的状态已经移动了,可能是在他们正在做的一些操作中。实际上执行工作的对象被复制然后被删除,对吧?由于移动与线程的执行异步,因此这似乎是个坏消息。
我问是因为我希望能够保留一组对象,每个对象都运行自己的线程。这些对象表示附加到系统的模块。我希望能够即时添加和分离模块。如果将对象存储在集合中不是一个好主意,那么替代方案是什么?我是否必须在堆上分配它们并将指针存储在我的集合中?
如果这根本不是问题,您能解释一下原因吗?
最佳答案
在reference :
Launching threads
A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor. The object is then copied into internal storage, and invoked on the newly-created thread of execution. If the object must not (or cannot) be copied, then boost::ref can be used to pass in a reference to the function object. In this case, the user of Boost.Thread must ensure that the referred-to object outlives the newly-created thread of execution.
由于复制了线程参数,因此在所有线程启动后移动 vector 不会有问题。
关于c++ - 如果一个线程正在执行的仿函数被移动会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010383/