c++11 动态创建线程
时间: 2023-12-08 12:37:26 浏览: 32
以下是C++11动态创建线程的两种方法:
1. 使用共享指针获取线程返回值
```cpp
#include <iostream>
#include <vector>
#include <thread>
#include <algorithm>
using namespace std;
int main() {
vector<thread> vThread;
vector<int*> nRst(5);
for (size_t i = 0; i < 5; i++) {
nRst[i] = new int(0);
}
for (int i = 0; i < 5; i++) {
int a = 1;
int b = 2;
int *sumTemp = nRst[i];
vThread.push_back(thread([a, b, i , sumTemp]() {
*sumTemp = (a + b + i);
}));
}
std::for_each(vThread.begin(), vThread.end(), [](thread& thr) {
thr.join();
});
for (size_t i = 0; i < 5; i++) {
cout << *nRst[i] << endl;
delete nRst[i];
}
return 0;
}
```
2. 使用promise+future在thread和Lambda下返回值
```cpp
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int main() {
int a = 1;
int b = 2;
std::promise<int> promiseObj;
std::future<int> futureObj = promiseObj.get_future();
std::thread thr = thread([a, b, &promiseObj]() {
promiseObj.set_value(a + b);
});
thr.join();
int sum = futureObj.get();
cout << sum << endl;
return 0;
}
```