DEV Community

海前 王
海前 王

Posted on

future

#include <chrono>
#include <future>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>

void accumulate(std::vector<int>::iterator first,
    std::vector<int>::iterator last,
    std::promise<int> accumulate_promise)
{
    int sum = std::accumulate(first, last, 0);
    accumulate_promise.set_value(sum); // Notify future
}

void do_work(std::promise<void> barrier)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    barrier.set_value();
}

int main()
{
    // Demonstrate using promise<int> to transmit a result between threads.
    std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
    std::promise<int> accumulate_promise;
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
        std::move(accumulate_promise));

    // future::get() will wait until the future has a valid result and retrieves it.
    // Calling wait() before get() is not needed
    // accumulate_future.wait(); // wait for result
    std::cout << "result=" << accumulate_future.get() << '\n';
    work_thread.join(); // wait for thread completion

    // Demonstrate using promise<void> to signal state between threads.
   std::promise<void> barrier;
    std::future<void> barrier_future = barrier.get_future();
    std::thread new_work_thread(do_work, std::move(barrier));
    barrier_future.wait();
    new_work_thread.join();

}



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;
}


#include <iostream>
 #include <future>
 #include <thread>
 #include <exception>  // std::make_exception_ptr
 #include <stdexcept>  // std::logic_error

void catch_error(std::future<void> &future) {
    try {
       future.get();
    } catch (std::logic_error &e) {
       std::cerr << "logic_error: " << e.what() << std::endl;
   }
}

int main() {
    std::promise<void> promise;
    std::future<void> future = promise.get_future();

    std::thread thread(catch_error, std::ref(future));
    // 自定义异常需要使用make_exception_ptr转换一下
    promise.set_exception(
       std::make_exception_ptr(std::logic_error("caught")));

      thread.join();
     return 0;
}

#include <iostream>                // std::cout

#include <thread>                // std::thread

#include <mutex>                // std::mutex, std::unique_lock

#include <condition_variable>    // std::condition_variable



std::mutex mtx; // 全局互斥锁.

std::condition_variable cv; // 全局条件变量.

bool ready = false; // 全局标志位.



void do_print_id(int id)

{

    std::unique_lock <std::mutex> lck(mtx);

    while (!ready) // 如果标志位不为 true, 则等待...

        cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,

    // 线程被唤醒, 继续往下执行打印线程编号id.

    std::cout << "thread " << id << '\n';

}



void go()

{

    std::unique_lock <std::mutex> lck(mtx);

    ready = true; // 设置全局标志位为 true.

    cv.notify_all(); // 唤醒所有线程.

}



int main()

{

    std::thread threads[10];

    // spawn 10 threads:

    for (int i = 0; i < 10; ++i)

        threads[i] = std::thread(do_print_id, i);



    std::cout << "10 threads ready to race...\n";

    go(); // go!



    for (auto& th : threads)

        th.join();



    return 0;

}

// ConsoleApplication25.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <future>
#include <iostream>
#include <random>
#include <thread>
using namespace std;
int dosomething(char c)
{
    default_random_engine dre(c);
    uniform_int_distribution<int> id(10, 1000);
    for(int i=0;i<20;++i)
    {
        //cout << "id(dre)= " << id(dre) << "\n";
        this_thread::sleep_for(chrono::milliseconds(id(dre)));
        cout.put(c).flush();
    }
    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 <<( result1 + result2);
    cout << result;
}
// 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

Top comments (0)