DEV Community

海前 王
海前 王

Posted on

future

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <future>
#include <iostream>
#include <list>
#include <random>
#include <thread>
[[noreturn]]
void task1()
{
    std::list<int> v;
    while (true)
    {
        for(int i=0;i<1000000;i++)
        {
            v.push_back(i);
        }
        std::cout.put(',').flush();
        static int j = 0;
        if(j++>10)
        {
            break;
        }
    }
}
int main()
{
    std::future<void> f1 (std::async(task1));
    std::cin.get();
    f1.get();

}



Enter fullscreen mode Exit fullscreen mode


cpp

include <iostream>
#include <future>
#include <thread>
#include <unistd.h>
#include<chrono>
void set_promise(std::promise<int>& p) {
    std::cout << "set_promise begin." << std::endl;
    sleep(5);
    p.set_value(100); 
    std::cout << "set_promise end." << std::endl;
}

int main() {
    std::promise<int> p;
    // 将promise和future绑定,这一步就是允诺future,未来会有人对promise赋值
    std::future<int> f = p.get_future();
    std::thread t(&set_promise, std::ref(p));
    std::cout<<"wait ready111:" << std::endl;
    auto status = f.wait_for(std::chrono::milliseconds(1000));//等待1s,结束等待时状态未改变,返回值为timeout
    std::cout<<"wait ready222:" << static_cast<int>(status) <<std::endl;
    status = f.wait_for(std::chrono::milliseconds(5000));//等待5s,结束等待时,状态已经变为ready
    std::cout<<"wait ready333:" << static_cast<int>(status) <<std::endl;
    std::cout << f.get() << std::endl;    // 通过get 拿到promise set的value
t.join();
return 0;
}

// ConsoleApplication25.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <future>
#include <iostream>
#include <random>
#include <thread>
#include <mutex>

using namespace std;

static int pp = 0;
static mutex mtx;

int dosomething(char c)
{
    default_random_engine dre(c);
    uniform_int_distribution<int> id(10, 1000);
    for (int i = 0; i < 20; ++i)
    {
        this_thread::sleep_for(chrono::milliseconds(id(dre)));
        {
            lock_guard<mutex> lock(mtx);
            cout.put(c).flush();
            pp++;
        }
    }
    return c;
}

int fun1()
{
    return dosomething('-');
}

int fun2()
{
    return dosomething('+');
}

int main()
{
    std::cout << "Hello World!\n";
    std::future<int> result1(std::async(fun1));
    int result2 = fun2();
    int result = result1.get() + result2;
    cout <<"\n" << result << "\n";
    cout << pp;
}

Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode

Top comments (0)