xml*_*lmx 15 c++ standards multithreading object-lifetime c++11
#include <thread>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
void f(const vector<string>& coll)
{
this_thread::sleep_for(1h);
//
// Is coll guaranteed to be valid before exiting this function?
//
}
int main()
{
{
vector<string> coll(1024 * 1024 * 100);
thread(f, coll).detach();
}
//
// I know std::thread will copy arguments into itself by default,
// but I don't know whether these copied objects are still valid
// after the std::thread object has been destroyed.
//
while (true);
}
Run Code Online (Sandbox Code Playgroud)
通过引用将参数传递给std :: thread函数是否安全?
正如@TC 的评论,您没有传递对线程的引用,您只需在线程中复制向量:
thread(f, coll).detach(); // It's NOT pass by reference, but makes a copy.
Run Code Online (Sandbox Code Playgroud)
如果你真的想通过引用传递,你应该这样写:
thread(f, std::ref(coll)).detach(); // Use std::ref to pass by reference
Run Code Online (Sandbox Code Playgroud)
然后,如果线程尝试访问向量,代码将出现段错误,因为当线程运行时,向量很可能已经被破坏(因为它在主程序中超出了它的范围)。
所以你的问题:
通过引用将参数传递给
std::thread函数是否安全?
退出这个函数之前保证coll有效吗?
coll的构造函数时,因为是一个对象,所以它被复制。该副本本质上是向量(因此它成为右值),它将在线程执行期间绑定到参数 in 。(感谢@Praetorian 的评论)std::threadmaincolldecaydecaymovecollf通过引用将参数传递给函数是否安全std::thread?
decay复制,因此您实际上从未通过引用传递任何内容std::thread。参考std::decay: http: //www.cplusplus.com/reference/type_traits/decay/
std::thread