标签:blog 使用 os io for 2014 cti 代码
#include <iostream> #include <thread> #include <vector> #include <algorithm> #include <cassert> int main() { std::vector<std::thread> workers; for (int i = 0; i < 5; i++) { auto t = std::thread([i]() { std::cout << "thread function: " << i << "\n"; }); workers.push_back(std::move(t)); } std::cout << "main thread\n"; std::for_each(workers.begin(), workers.end(), [](std::thread &t) { assert(t.joinable()); t.join(); }); return 0; }运行结果为:
#include <iostream> #include <thread> #include <vector> #include <algorithm> #include <cassert> void task(int i) { std::cout<<"worker : "<<i<<std::endl; } int main() { std::vector<std::thread> workers; for (int i = 0; i < 5; i++) { auto t = std::thread(&task, i); workers.push_back(std::move(t)); } std::cout << "main thread" << std::endl; std::for_each(workers.begin(), workers.end(), [](std::thread &t) { assert(t.joinable()); t.join(); }); return 0; }运行结果为:
void task(int &i) { std::cout << "worker : " << i << "\n"; }与此同时,线程的构造函数同样需要相应的修改
C++11线程指南(五)--线程的移动语义实现,布布扣,bubuko.com
标签:blog 使用 os io for 2014 cti 代码
原文地址:http://blog.csdn.net/shltsh/article/details/38454273