带返回的线程池
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
#include <vector>
#include <functional>
#include <algorithm>
int foo(int x) {
std::this_thread::sleep_for(std::chrono::seconds(2));
return x * x;
}
int main() {
std::vector<std::future<int>> results;
std::vector<int> inputs = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto input : inputs) {
results.push_back(std::async(std::launch::async, foo, input));
}
std::for_each(results.begin(), results.end(), [](std::future<int>& f) {
std::cout << f.get() << std::endl;
});
return 0;
}
返回的线程
#include<thread>
#include <future>
int fun(){
static int a = 10;
a = a+1;
QThread::sleep(5);
return a;
}
int main(int argc, char *argv[])
{
auto res = std::async(fun);
std::cout << "1111111111"<<std::endl;
std::cout << res.get() << '\n';
std::cout << "2222222222"<<std::endl;
}
结果:
1111111111
11
2222222222