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
相关文章
|
2月前
|
设计模式 运维 监控
并发设计模式实战系列(4):线程池
需要建立持续的性能剖析(Profiling)和调优机制。通过以上十二个维度的系统化扩展,构建了一个从。设置合理队列容量/拒绝策略。动态扩容/优化任务处理速度。检查线程栈定位热点代码。调整最大用户进程数限制。CPU占用率100%
176 0
|
2月前
|
设计模式 监控 前端开发
并发设计模式实战系列(15):Future/Promise
🌟 大家好,我是摘星!🌟今天为大家带来的是并发设计模式实战系列,第十五章,废话不多说直接开始~
38 0
|
8月前
|
存储 前端开发
除了 Promise.all(),还有哪些方法可以处理异步并发操作?
在上述示例中,`concurrentPromises` 函数接受一个Promise数组和最大并发数作为参数,通过手动控制并发执行的Promise数量,实现了对异步操作的并发控制,并在所有Promise完成后返回结果数组。
|
8月前
|
前端开发 JavaScript
如何使用 Promise 处理异步并发操作?
通过使用 `Promise.all()` 和 `Promise.race()` 方法,可以灵活地处理各种异步并发操作,根据不同的业务需求选择合适的方法来提高代码的性能和效率,同时也使异步代码的逻辑更加清晰和易于维护。
|
8月前
|
前端开发 数据处理
如何使用 Promise.all() 处理异步并发操作?
使用 `Promise.all()` 可以方便地处理多个异步并发操作,提高代码的执行效率和可读性,同时通过统一的 `.catch()` 方法能够有效地处理异步操作中的错误,确保程序的稳定性。
|
2月前
|
存储 缓存 安全
JUC并发—11.线程池源码分析
本文主要介绍了线程池的优势和JUC提供的线程池、ThreadPoolExecutor和Excutors创建的线程池、如何设计一个线程池、ThreadPoolExecutor线程池的执行流程、ThreadPoolExecutor的源码分析、如何合理设置线程池参数 + 定制线程池。
JUC并发—11.线程池源码分析
|
2月前
|
机器学习/深度学习 消息中间件 存储
【高薪程序员必看】万字长文拆解Java并发编程!(9-2):并发工具-线程池
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发编程中的强力并发工具-线程池,废话不多说让我们直接开始。
102 0
|
8月前
|
安全
List并发线程安全问题
【10月更文挑战第21天】`List` 并发线程安全问题是多线程编程中一个非常重要的问题,需要我们认真对待和处理。只有通过不断地学习和实践,我们才能更好地掌握多线程编程的技巧和方法,提高程序的性能和稳定性。
443 59
|
8月前
|
安全 Java
线程安全的艺术:确保并发程序的正确性
在多线程环境中,确保线程安全是编程中的一个核心挑战。线程安全问题可能导致数据不一致、程序崩溃甚至安全漏洞。本文将分享如何确保线程安全,探讨不同的技术策略和最佳实践。
125 6
|
8月前
|
安全 Java 开发者
Java 多线程并发控制:深入理解与实战应用
《Java多线程并发控制:深入理解与实战应用》一书详细解析了Java多线程编程的核心概念、并发控制技术及其实战技巧,适合Java开发者深入学习和实践参考。
179 8