use*_*229 1 multithreading c++11
我正在尝试填充我的矢量:
...
auto f = std::bind(&ScheduledExecutor::complete_after, std::placeholders::_1, std::placeholders::_2);
threadPoolVector.push_back(std::thread(f, this, delay));
...
Run Code Online (Sandbox Code Playgroud)
如何在将其推送到向量之前分离添加线程?
使用C++ 11或更高版本,您可以利用移动语义.当它们不是绝对必要时,最好避免使用指针,甚至是智能指针.
您可以创建std::thread对象并使用std::move函数移动它:
std::vector<std::thread> pool;
std::thread th(f);
pool.push_back(std::move(th));
Run Code Online (Sandbox Code Playgroud)
您还可以使用std::vector::emplace_back函数std::thread直接在std::vector实例中创建对象.
然后你可以使用for以下方法加入或分离它们:
for (auto& t : pool)
t.detach(); // or t.join() to join it
Run Code Online (Sandbox Code Playgroud)
或使用std::vector::at或std::vector::operator[]函数访问每个元素.
| 归档时间: |
|
| 查看次数: |
1305 次 |
| 最近记录: |