c++ - 如果一个线程正在执行的仿函数被移动会发生什么?

标签 c++ stl thread-safety functor

假设我有一个仿函数 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/

相关文章:

c++ - C++ 中的二进制读/写任意 std::vector<std::vector<int>>

c++ - 函数不改变传递的指针 C++

java - 我如何确保写入发生在同一存储桶和同一键上的不同线程同时读取 concurrenthashmap 之前?

java - 线程 volatile

c++ - 指向数组边界外的内存地址

c++ - 如何强制我的 std::map 释放使用的内存?

c++ - 当我从 main 调用 ctor 时,为什么在范围结束之前调用 dtor? (实验性的)

自己的容器类的 C++ 迭代器和 const_iterator 问题

c++ - stringstream->rdbuf()->pubsetbuf 没有设置缓冲区

随机数生成器的 C++11 线程安全