创建vector <thread>

Tor*_*ous 0 c++

我只是想创建一个std::vector线程并运行它们.

码:

thread t1(calc, 95648, "t1");
thread t2(calc, 54787, "t2");
thread t3(calc, 42018, "t3");
thread t4(calc, 75895, "t4");
thread t5(calc, 81548, "t5");

vector<thread> threads { t1, t2, t3, t4, t5 };
Run Code Online (Sandbox Code Playgroud)

错误:"函数std :: thread :: thread(const std :: thread&)"(在"C:\ Program Files(x86)\ Microsoft Visual Studio 12.0\VC\include\thread"的第70行声明)不能引用 - 它是一个已删除的函数

thread(const thread&) = delete;
Run Code Online (Sandbox Code Playgroud)

什么似乎是问题?

Ker*_* SB 5

由于线程不可复制,但可移动,我建议采用以下方法:

std::vector<std::thread> threads;

threads.emplace_back(calc, 95648, "t1");
threads.emplace_back(calc, 54787, "t2");
threads.emplace_back(calc, 42018, "t3");
threads.emplace_back(calc, 75895, "t4");
threads.emplace_back(calc, 81548, "t5");
Run Code Online (Sandbox Code Playgroud)

  • 因为`thread`对象不能被复制(当你将值插入到向量中时,它被复制),但是使用`emplace`,它就会直接在向量本身中创建. (3认同)