C++创建后台线程并返回值

1.用到函数模板std::async,和类模板std::future

2工作原理:std::async用来启动一个异步任务,启动任务之后,它返回一个std::future对象,这个对象含有线程入口函数所返回的结果(线程返回的结果),线程执行完,我们可以通过调用future对象的成员函数get()来获取结果,std::future就是提供了一种访问异步操作结果的机制。

3.代码如下:

 

#include <iostream>
#include<thread>
#include<string>
#include<vector>
#include<algorithm>
#include<windows.h>
#include<list>
#include<mutex>
#include<future>
#include<chrono>

int ThreadFun()
{
    std::cout << "thread start     " << "thread id" << std::this_thread::get_id() <<std::endl;
    std::chrono::milliseconds dura(5000);
    std::this_thread::sleep_for(dura);
    std::cout << "thread end     " << "thread id" << std::this_thread::get_id() << std::endl;
    return 5;
}

int main()
{
    std::cout << "main thread start     " << "thread id" << std::this_thread::get_id() << std::endl;
    std::future<int> result = std::async(ThreadFun);

    std::cout << "执行其他代码" << std::endl;

    //int nRes = result.get();       //当线程没有运行完时,他会一直阻塞在这,直到线程结束。
    //std::cout << "thread work result:" << nRes << std::endl;

    return 0;
}
View Code

4.注意:当线程没有运行完,代码会一直阻塞在这get()函数这,直到线程结束。

5.了解std::launch

  1.std::launch::async

  std::async(std::launch::deferred, ThreadFun),这个函数当没有第一个参数时,默认第一个参数是std::launch::async,表示创建一个线程并且立即执行。

  2.std::launch::deferred

  这是个枚举,表示线程入口函数调用被延迟到std::future的wait()或者get()寒素调用时才执行,

    (1)如果wait()或者get()函数没有调用,那么线程就不创建,更不执行线程函数。

    (2)如果调用了wait()或者get(),线程也根本就没有创建,实际上,线程函数会在主线程中把线程函数执行掉。

  如下代码,子线程和主线的id一样

#include <iostream>
#include<thread>
#include<string>
#include<vector>
#include<algorithm>
#include<windows.h>
#include<list>
#include<mutex>
#include<future>
#include<chrono>

int ThreadFun()
{
    std::cout << "thread start     " << "thread id" << std::this_thread::get_id() <<std::endl;
    std::chrono::milliseconds dura(5000);
    std::this_thread::sleep_for(dura);
    std::cout << "thread end     " << "thread id" << std::this_thread::get_id() << std::endl;
    return 5;
}

int main()
{
    std::cout << "main thread start     " << "thread id" << std::this_thread::get_id() << std::endl;
    std::future<int> result = std::async(std::launch::deferred, ThreadFun);

    result.wait();
    std::cout << "执行其他代码" << std::endl;
    //int nRes = result.get();       //当线程没有运行完时,他会一直阻塞在这,直到线程结束。
    //std::cout << "thread work result:" << nRes << std::endl;

    return 0;
}
View Code

 6.   std::async和std::thread的区别

  (1)如果系统资源紧张,std::thread方式创建线程的话,则可能创建失败,导致程序崩溃。

  (2)std::async创建线程时,一般不会导致程序崩溃,如果系统资源紧张,那么std::async就不会创建线程,而是后续谁调用了result.get()来请求结果,那么这个异步任务就运行在执行这条get()语句的线程上。

posted @ 2020-08-23 23:03  zwj鹿港小镇  阅读(890)  评论(0)    收藏  举报