并发编程std::promise的使用及注意点

 

##### 注意:正确的使用promise要必须知道它什么时候会抛出异常

enum class future_errc {
    broken_promise             = /* promise已被析构*/,
    future_already_retrieved   = /* get_future()多次 */,
    promise_already_satisfied  = /* set_value()多次 */,
    no_state                   = /* future.get()已经成功,后面又future.get()了一次 */
};


>**example:**
 

#include <iostream>
#include <memory>
#include <thread>
#include <future>
#include <mutex>
#include <chrono>
#include <string>
static std::string  future_string[] =
{ "ready",
   "timeout",
   "deferred"
};

int main()
{
    auto func = [](std::shared_ptr<std::promise<int>> ptr) {
        std::cout << "[thread]" << ptr.use_count() << std::endl;
        std::cout << "[thread] will set_value after 4s" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(4));
        if (ptr != nullptr)
        {
            ptr->set_value(20);
            std::cout << "[thread] set value done111~ " << ptr.use_count() << std::endl;
            ptr = nullptr;
            std::cout << "[thread] set value done222~ " << ptr.use_count() << std::endl;
        }
    };

    std::thread th_;

    {
        //构建promise
        std::shared_ptr<std::promise<int>> sp = std::make_shared<std::promise<int>>();
        std::future<int> future = sp->get_future();
        std::future_status status;

        //创建线程, 以智能指针方式传递
        //以普通指针传递会有特殊情况,主线程等待超时都没等到函数退出
        //就会析构promise,此后线程中调用promise->setValue()就会报错
        th_ = std::thread(func, sp);

        try
        {
            //设置10s内轮询查看当前future状态
            for (int i = 0; i < 10; ++i)
            {
                status = future.wait_for(std::chrono::seconds(1));
                std::cout << "[main] ---> current status:  " << future_string[static_cast<int>(status)] << "\t" << i << "s" << std::endl;
                if (status == std::future_status::ready)
                {
                    std::cout << "[main get the promise result:   " << future.get() << std::endl;
                    break;  /*一定要退出,只能get一次,多次就会有异常*/
                }
            }
        }
        catch (const std::exception& e)
        {
            std::cerr << "error: " << e.what() << std::endl;
        }
        
                
        std::cout << "[main]  func will exit, start delete promise_________  " << sp.use_count() << std::endl;
    }

    th_.join();
    return 0;
}

#include <iostream>
#include <future>
#include <thread>
#include <chrono>
#include <mutex>
#include <atomic>

std::mutex mtx_;
std::atomic<bool>  stop_ = false;
int memory = 0;
std::shared_ptr<std::promise<int>>  sp_po = nullptr;

void test()
{
	while (!stop_)
	{
		std::unique_lock<std::mutex> lck(mtx_);
		if (sp_po != nullptr)
		{
			try {
				sp_po->set_value(memory);
                sp_po = nullptr;
			}
			catch (std::exception& ec)
			{
				std::cout << "error " << ec.what() << std::endl;
			}
		}			
		lck.unlock();
		
		std::cout << "thread set value " << memory << std::endl;
		memory++;		
		std::this_thread::sleep_for(std::chrono::milliseconds(500));
	}
}

int main()
{	
	std::thread th(test);

	while(1)
	{		
		std::unique_lock<std::mutex> lck(mtx_);		
		sp_po.reset(new std::promise<int>);
		lck.unlock();

		std::cout << "main get value: " << sp_po->get_future().get() << std::endl;
	}


	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何处惹尘埃~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值