异步实现的一些方式

异步实现的一些方式

其实主要就是用到std::future和std::async这些,记录一下异步耗时操作是否结束

事件循环实现

其实主要就是这一行代码

std::future<int> fut = std::async(std::launch::async, async_operation);
#include<iostream>
#include<future>
#include<thread>
#include<chrono>
#include<condition_variable>
#include<mutex>

// 事件循环实现异步
int async_operation() {
    // 模拟耗时操作,sleep 5s
    std::this_thread::sleep_for(std::chrono::seconds(5));
    return 42;
}

void on_result(int result) {
    std::cout << "Result of the async operation: "<< result<< std::endl;
}

int main() {
    // 使用std::async启动异步操作
    std::future<int> fut = std::async(std::launch::async, async_operation);

    // 在主线程中输出一条消息,表明异步操作已开始
    std::cout << "Async operation started."<< std::endl;

    // 使用事件循环检查异步操作是否已完成
    while (true) {
        // 表示最多等待100ms,如果异步操作完成了返回std::future_status::ready,否则返回std::future_status::timeout
        std::future_status status = fut.wait_for(std::chrono::milliseconds(100));

        if (status == std::future_status::ready) {
            // 异步操作已完成,获取结果并调用回调函数
            int result = fut.get();
            on_result(result);
            break;
        }

        // 在这里执行其他任务,例如处理用户输入、更新UI等
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    return 0;
}

回调函数实现

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

// 回调实现异步,2-2是不采用匿名表达式的方式
int async_operation() {
    // 模拟耗时操作
    std::this_thread::sleep_for(std::chrono::seconds(5));
    return 42;
}

void on_result(int result) {
    std::cout << "Result of the async operation: " << result << std::endl;
}

void async_callback(std::function<void(int)> callback) {
    // 启动一个新线程来执行异步操作
    std::thread t([callback]() {
        int result = async_operation();
        callback(result);  // 调用回调函数
    });

    // 分离线程,使主线程不再等待它完成
    t.detach();
}

int main() {
    // 在主线程中输出一条消息,表明异步操作已开始
    std::cout << "Async operation started." << std::endl;

    // 使用回调函数启动异步操作
    async_callback(on_result);
    while (true) {
        // 在这里执行其他任务,例如处理用户输入、更新UI等
        std::cout << "处理其他任务1" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "处理其他任务2" << std::endl;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值