async(), future, shared_futrue(), wait()的一个综合性例子

本文深入探讨了C++中的并发编程,使用`<future>`和`<thread>`库创建异步任务并管理共享未来。示例中展示了如何捕获异常、同步等待以及在多个线程间安全地操作共享数据。通过`async`启动任务,并使用`get`获取结果,同时展示了不同类型的等待策略,如`wait_for`和`wait_until`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先贴例子,具体知识后续补充。。。

#include <future>
#include <thread>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;

int& queryNumber (int& num)
{
    // read number
    cout << "read number: ";
    // int num;
    cin >> num; 

    // throw exception if none
    if (!cin) {
        throw runtime_error("no number read");
    }

    return num;
}

void doSomething (char c, shared_future<int&> f)
{
    try {
        // wait for number of characters to print
        int num = f.get();  // get result of queryNumber()

        for (int i=0; i<num; ++i) {
            this_thread::sleep_for(chrono::milliseconds(500));
            cout.put(c).flush();
        }
    }
    catch (const exception& e) {
        cerr << "EXCEPTION in thread " << this_thread::get_id()
                  << ": " << e.what() << endl;
    }
}

void ChangeNum(shared_future<int&> f) {
    // int& num = f.get();
    auto& num = f.get();
    cout << typeid(num).name() << endl;
    num += 4;
}

int main()
{
    try {
        int num;
        // start one thread to query a number
        // shared_future<int&> f = async(queryNumber,ref(num));
       auto f = async(queryNumber, ref(num)).share();

        // start three threads each processing this number in a loop
        auto f1 = async(ChangeNum, f);
        f1.wait();
        auto f2 = async(launch::async, doSomething, '+', f);
        auto f3 = async(launch::deferred, doSomething, '*', f);
        auto f4 = async(doSomething, '.', f);
        auto f5 = async(doSomething, '~', f);
		//注意:wait_for和wait_until不会启动一个被推迟的任务--线程
		//     如果f4被推迟了,这里直接返回future_status::deferred
        auto t = f4.wait_for(chrono::seconds(6)); 

        if ( t == future_status::ready) {
            cout << "f4 enter ready\n";
            f4.wait();
        }

        if (f5.wait_until(chrono::system_clock::now() + chrono::seconds(60)) == future_status::deferred) {
            cout << "f5 enters feferred.\n"; 
            f5.wait();
        }

        // wait for all loops to be finished
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        f5.get();
    }
    catch (const exception& e) {
        cout << "\nEXCEPTION: " << e.what() << endl;
    }
    cout << "\ndone" << endl;
}

输出:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值