C++并发与多线程(四)async、future、packaged_task、promise、shared_future(上)

简介: C++并发与多线程(四)async、future、packaged_task、promise、shared_future(上)

本文系列大部分来自c++11并发与多线程视频课程的学习笔记,系列文章有(不定期更新维护):


  • C++并发与多线程(一)线程传参
  • C++并发与多线程(二) 创建多个线程、数据共享问题分析、案例代码
  • C++并发与多线程(三)单例设计模式与共享数据分析、call_once、condition_variable使用
  • C++并发与多线程(四)async、future、packaged_task、promise、shared_future
  • C++并发与多线程(五)互斥量,atomic、与线程池

std::async、std::future创建后台任务并返回值


  之前,我们用std::thread创建一个线程,用join()等待这个线程结束,如果希望线程返回一个结果呢?

  std::async是一个函数模板,用来启动一个异步任务,启动起来一个异步任务之后,它返回一个std::future对象,这个对象也是个类模板。什么叫“启动一个异步任务”?就是自动创建一个线程,并开始 执行对应的线程入口函数,它返回一个std::future对象,这个std::future对象中就含有线程入口函数所返回的结果,我们可以通过调用future对象的成员函数get()来获取结果。

  “future”将来的意思,也有人称呼std::future提供了一种访问异步操作结果的机制,就是说这个结果你可能没办法马上拿到,但是在不久的将来,这个线程执行完毕的时候,你就能够拿到结果了,所以,大家这么理解:future中保存着一个值,这个值是在将来的某个时刻能够拿到。

#include <iostream>
#include <future>
using namespace std;
int mythread(){
    cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
    std::chrono::milliseconds dura(5000); // 休息五秒
    std::this_thread::sleep_for(dura);
    cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
    return 5;
}
int main(){
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(mythread); // 创建一个线程并开始执行
    cout << "continue ....." << endl;
    cout << "res.get() is : " << res.get() << endl; // 执行到get的时候,会卡在此行,等待mythread执行完毕。
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  程序输出结果为:

main started and the thread id is 0x1000e3d40
continue .....
res.get() is : mythread() started and the thread id is 0x16fe87000
mythread() ended and the thread id is 0x16fe87000
5
main ended and the thread id is 0x1000e3d40

  std::future对象的get()成员函数会等待线程执行结束并返回结果,拿不到结果它就会一直等待,感觉有点像join()但是,它是可以获取结果的。而std::future对象的wait()成员函数,用于等待线程返回,本身并不返回结果,这个效果和std::threadjoin()更像。

#include <iostream>
#include <future>
using namespace std;
int mythread(){
    cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
    std::chrono::milliseconds dura(5000); // 休息五秒
    std::this_thread::sleep_for(dura);
    cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
    return 5;
}
int main(){
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(mythread); // 创建一个线程并开始执行
    cout << "continue ....." << endl;
    //cout << "res.get() is : " << res.get() << endl; // 执行到get的时候,会卡在此行,等待mythread执行完毕。
    res.wait(); // 等待线程返回,但是拿不到返回值,类似join。
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  同样的,我们可以使用类成员函数作为线程的入口函数:

#include <iostream>
#include <future>
using namespace std;
class A{
public:
    int mythread(int num){
        cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
        cout << "num is: " << num << endl;
        std::chrono::milliseconds dura(5000); // 休息五秒
        std::this_thread::sleep_for(dura);
        cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
        return 5;
    }
};
int main(){
    A a;
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(&A::mythread, &a, 10); // 第二个参数是对象引用,如果不用引用的话,就会创建一个新的类A的对象。
    cout << "continue ....." << endl;
    cout << "res.get() is : " << res.get() << endl; // 执行到get的时候,会卡在此行,等待mythread执行完毕。
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  我们可以通过向std::async()额外传递一个参数,该参数是std::launch类型(枚举类型),来达到一些特殊的目的:

  1. std::lunch::deferred:(defer推迟,延期)表示线程入口函数的调用会被延迟,一直到std::futurewait()或者get()函数被调用时(由主线程调用)才会执行;如果wait()或者get()没有被调用,则不会执行。
#include <iostream>
#include <future>
using namespace std;
class A{
public:
    int mythread(int num){
        cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
        cout << "num is: " << num << endl;
        std::chrono::milliseconds dura(5000); // 休息五秒
        std::this_thread::sleep_for(dura);
        cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
        return 5;
    }
};
int main(){
    A a;
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(std::launch::deferred,&A::mythread, &a, 10); // 第二个参数是对象引用,如果不用引用的话,就会创建一个新的类A的对象。
    cout << "continue ....." << endl;
    cout << "res.get() is : " << res.get() << endl; // 执行到get的时候,会卡在此行,等待mythread执行完毕。
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  程序输出结果为:

main started and the thread id is 0x1000e7d40
continue .....
res.get() is : mythread() started and the thread id is 0x1000e7d40
num is: 10
mythread() ended and the thread id is 0x1000e7d40
5
main ended and the thread id is 0x1000e7d40
Program ended with exit code: 0

  可以看到主线程id0x1000e7d40,子线程id同样为0x1000e7d40,也就是说,实际上根本就没有创建新线程。std::lunch::deferred意思时延迟调用,并没有创建新线程,是在主线程中调用的线程入口函数。上述代码永远都会先打印出continue…,然后才会打印出mythread() startmythread() end等信息。

  1. std::launch::async,在调用async函数的时候就开始创建新线程。
#include <iostream>
#include <future>
using namespace std;
class A{
public:
    int mythread(int num){
        cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
        cout << "num is: " << num << endl;
        std::chrono::milliseconds dura(5000); // 休息五秒
        std::this_thread::sleep_for(dura);
        cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
        return 5;
    }
};
int main(){
    A a;
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(std::launch::async,&A::mythread, &a, 10); // 第二个参数是对象引用,如果不用引用的话,就会创建一个新的类A的对象。
    cout << "continue ....." << endl;
    cout << "res.get() is : " << res.get() << endl; // 执行到get的时候,会卡在此行,等待mythread执行完毕。
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  程序输出结果为:

main started and the thread id is 0x1000e7d40
continue .....
res.get() is : mythread() started and the thread id is 0x16fe87000
num is: 10
mythread() ended and the thread id is 0x16fe87000
5
main ended and the thread id is 0x1000e7d40
Program ended with exit code: 0

std::packaged_task

  std::packaged_task打包任务,把任务包装起来。也是一个类模板,它的模板参数是各种可调用对象,通过packaged_task把各种可调用对象包装起来,方便将来作为线程入口函数来调用。

#include <iostream>
#include <future>
using namespace std;
int mythread(int num){
    cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
    cout << "num is: " << num << endl;
    std::chrono::milliseconds dura(5000); // 休息五秒
    std::this_thread::sleep_for(dura);
    cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
    return 5;
}
int main(){
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    //我们把函数mythread通过packaged_task包装起来。参数是一个int,返回值类型是int
    std::packaged_task<int(int)> mypt(mythread);
    std::thread mythread(std::ref(mypt), 10); // 线程直接开始执行,第二个参数为线程入口参数
    mythread.join();
    //std::future对象里包含有线程入口函数的返回结果,这里result保存mythread返回的结果。
    std::future<int> res = mypt.get_future();
    cout << "res.get() is : " << res.get() << endl;
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  输出结果为:

main started and the thread id is 0x1000e3d40
mythread() started and the thread id is 0x16fe87000
num is: 10
mythread() ended and the thread id is 0x16fe87000
res.get() is : 5
main ended and the thread id is 0x1000e3d40
Program ended with exit code: 0

  可调用对象可由函数换成lambda表达式:

#include <iostream>
#include <future>
using namespace std;
int main(){
    cout << "main started and the thread id is " << std::this_thread::get_id() << endl;
    //我们把函数mythread通过packaged_task包装起来。参数是一个int,返回值类型是int
    std::packaged_task<int(int)> mypt([](int num){
        cout << "mythread() started and the thread id is " << std::this_thread::get_id() << endl;
        cout << "num is: " << num << endl;
        std::chrono::milliseconds dura(5000); // 休息五秒
        std::this_thread::sleep_for(dura);
        cout << "mythread() ended and the thread id is " << std::this_thread::get_id() << endl;
        return 5;
    });
    std::thread mythread(std::ref(mypt), 10); // 线程直接开始执行,第二个参数为线程入口参数
    mythread.join();
    //std::future对象里包含有线程入口函数的返回结果,这里result保存mythread返回的结果。
    std::future<int> res = mypt.get_future();
    cout << "res.get() is : " << res.get() << endl;
    cout << "main ended and the thread id is " << std::this_thread::get_id() << endl;
}

  输出结果为:

main started and the thread id is 0x1000e3d40
mythread() started and the thread id is 0x16fe87000
num is: 10
mythread() ended and the thread id is 0x16fe87000
res.get() is : 5
main ended and the thread id is 0x1000e3d40
Program ended with exit code: 0
相关文章
|
9月前
|
前端开发 JavaScript API
一文吃透 Promise 与 async/await,异步编程也能如此简单!建议收藏!
在前端开发中,异步编程至关重要。本文详解了同步与异步的区别,通过生活化例子帮助理解。深入讲解了 Promise 的概念、状态及链式调用,并引入 async/await 这一语法糖,使异步代码更清晰易读。还介绍了多个异步任务的组合处理方式,如 Promise.all 与 Promise.race。掌握这些内容,将大幅提升你的异步编程能力,写出更优雅、易维护的代码,助力开发与面试!
442 0
一文吃透 Promise 与 async/await,异步编程也能如此简单!建议收藏!
|
9月前
|
前端开发 JavaScript API
JavaScript异步编程:从Promise到async/await
JavaScript异步编程:从Promise到async/await
655 204
|
10月前
|
Java API 调度
从阻塞到畅通:Java虚拟线程开启并发新纪元
从阻塞到畅通:Java虚拟线程开启并发新纪元
483 83
|
10月前
|
存储 Java 调度
Java虚拟线程:轻量级并发的革命性突破
Java虚拟线程:轻量级并发的革命性突破
505 83
|
12月前
|
机器学习/深度学习 消息中间件 存储
【高薪程序员必看】万字长文拆解Java并发编程!(9-2):并发工具-线程池
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发编程中的强力并发工具-线程池,废话不多说让我们直接开始。
415 0
|
12月前
|
设计模式 运维 监控
并发设计模式实战系列(4):线程池
需要建立持续的性能剖析(Profiling)和调优机制。通过以上十二个维度的系统化扩展,构建了一个从。设置合理队列容量/拒绝策略。动态扩容/优化任务处理速度。检查线程栈定位热点代码。调整最大用户进程数限制。CPU占用率100%
631 0
|
12月前
|
设计模式 监控 前端开发
并发设计模式实战系列(15):Future/Promise
🌟 大家好,我是摘星!🌟今天为大家带来的是并发设计模式实战系列,第十五章,废话不多说直接开始~
252 0
|
7月前
|
设计模式 缓存 安全
【JUC】(6)带你了解共享模型之 享元和不可变 模型并初步带你了解并发工具 线程池Pool,文章内还有饥饿问题、设计模式之工作线程的解决于实现
JUC专栏第六篇,本文带你了解两个共享模型:享元和不可变 模型,并初步带你了解并发工具 线程池Pool,文章中还有解决饥饿问题、设计模式之工作线程的实现
436 2
|
前端开发
使用 async/await 结合 try/catch 处理 Promise.reject()抛出的错误时,有什么需要注意的地方?
使用 async/await 结合 try/catch 处理 Promise.reject()抛出的错误时,有什么需要注意的地方?
677 155