C++线程池和带返回的线程

带返回的线程池

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值