C11并发 std::promise<T>

头文件中包含了以下几个类和函数:

Providers 类:std::promise, std::package_task
Futures 类:std::future, shared_future.
Providers 函数:std::async()
其他类型:std::future_error, std::future_errc, std::future_status, std::launch.
std::promise 类介绍

promise 对象可以保存某一类型 T 的值,该值可被 future 对象读取(可能在另外一个线程中),因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。

可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state)

promise 对象是异步 Provider,它可以在某一时刻设置共享状态的值。
future 对象可以异步返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready,然后才能获取共享状态的值。
下面以一个简单的例子来说明上述关系

void print_int(std::future<int>& fut) {
    try {
        std::cout << " fut.get()" << '\n';
        int x = fut.get();
        std::cout << "value: " << x << '\n';
    }
    catch (std::exception& e) {
        std::cout << "[exception caught: " << e.what() << "]\n";
    }
}

int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread th2(print_int, std::ref(fut));
    Sleep(5000);
    prom.set_value(11);
    th2.join();

    return 0;
}

prom.get_future()通过 get_future 来获取与该 promise 对象相关联的 future 对象

std::future .get()阻塞当前线程 直到有值:std::promise.set_value

例2,反过来,适用socket异步通信中收包同步


#include "stdafx.h"

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
#include <windows.h>
void get_int(std::promise<int>& prom) { 
    try {
                                 // sets failbit if input is not int
        Sleep(5000);
        prom.set_value(123);

    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}


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

    std::thread(get_int, std::ref(prom)).detach();  

    std::cout << "value:" << fut.get()<< std::endl;
    return 0;
}

std::promise set_exception实现跨线程异常传递

void get_int(std::promise<int>& prom) { 
    try {
                                 // sets failbit if input is not int
        Sleep(5000);
        throw std::logic_error("merro");
        prom.set_value(123);


    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}


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

    std::thread(get_int, std::ref(prom)).detach();  

    try
    {
        std::cout << "value:" << fut.get() << std::endl;
    }
    catch (const std::exception& e)
    {
        std::cout << "erro:" << e.what() << std::endl;
    }

    return 0;
}

禁止复制拷贝,用转移语义:


#include "stdafx.h"

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
#include <windows.h>
#include <stdexcept>
#include <vector>
using namespace std;
vector<std::promise<int> > globalArray;
void get_int(std::promise<int>& prom) { 
    try {
                                 // sets failbit if input is not int
        Sleep(1000);
        throw std::logic_error("merro");
        prom.set_value(123);


    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}


int main()
{
    for (int i=0;i<10;i++)
    {
        std::promise<int> prom;
        globalArray.push_back(std::move(prom));
    }



        for (auto &x : globalArray)
        {
            try
            {

                std::thread(get_int, std::ref(x)).detach();
                std::cout << "value:" << x.get_future().get() << std::endl;
            }
            catch (const std::exception& e)
            {
                std::cout << "erro:" << e.what() << std::endl;
            }
        }




    return 0;
}

或者更方便的设计:(注 future .get的时候才会获取异常)


#include "stdafx.h"

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
#include <windows.h>
#include <stdexcept>
#include <vector>
#include <memory>
using namespace std;
vector<std::shared_ptr<std::promise<int>> > globalArray;
void get_int(std::shared_ptr<std::promise<int>> prom) {
    try {
                                 // sets failbit if input is not int

        throw std::logic_error("merro");
        prom->set_value(123);


    }
    catch (std::exception&) {
        prom->set_exception(std::current_exception());
    }
}


int main()
{
    for (int i = 0; i < 10; i++)
    {
        auto pprom = std::make_shared<std::promise<int>>();


        globalArray.push_back(pprom);
        try
        {
            std::thread(get_int, pprom).detach();

        }
        catch (const std::exception& e)
        {
            std::cout << "erro0:" << e.what() << std::endl;
        }
    }

    Sleep(1000);

    for (auto &x : globalArray)
    {

        try
        {
            std::cout << "value:" << x->get_future().get() << std::endl;

        }
        catch (const std::exception& e)
        {
            std::cout << "erro:" << e.what() << std::endl;
        }



    }




    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值