C++11多线程之future(一)

// ConsoleApplication5.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include<random>
#include<iostream>
#include<vector>
#include<thread>
#include<algorithm>
#include<future>
using namespace std;

class A
{
public:
    void mythread()
    {
        cout << "子线程开始了,id为:" << this_thread::get_id() << endl;
        this_thread::sleep_for(chrono::seconds(5));
        cout << "子线程结束了" << endl;
    }
};
int main()
{
    A a;
    //future<void> s = async(&A::mythread,&a);
    cout << "主线程的id:" << this_thread::get_id() << endl;
    //一旦闯入了第一个参数launch::deferred,如果不调用get()或者wait,那么子线程不会被调用.
    future<void> s = async(launch::deferred,&A::mythread, &a);
    //wait_for()在这里的等待
    //如果上面的async()函数的第一个参数为launch::deferred,那么这里的wait_for根本不会执行,直接执行接下来的语句
    future_status status = s.wait_for(chrono::seconds(6));
    if (status==future_status::timeout)
    {
        cout << "超时了" << endl;
    }
    else if (status ==future_status::ready)
    {
        cout << "子线程执行完毕了" << endl;
    }
    else if (status == future_status::deferred)
    {
        //只有当async()的第一个参数为launch::deferred时,才会执行到这里
        cout << "子线程被延迟执行了" << endl;
        s.get();//子线程一直被延迟到这里才开始执行,一旦延迟,系统也不会创建一个新的线程,而是在主线程中进行调用。
    }
    return 0;
}
原文地址:https://www.cnblogs.com/SunShine-gzw/p/13535219.html