其实主要就是用到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;
}