当前位置: 首页 > news >正文

asio监听eventfd

c++ - Does BOOST asio supports eventfd? like epoll - Stack Overflow

asio的官方example并没有asio监听eventfd的例子,但asio支持posix::stream_descriptor, 

如果将eventfd包装成posix::stream_descriptor,并注册到io_context里,那就应该支持了。 

例子如下:

#include <array>
#include <iostream>
#include <thread>
#include <asio.hpp>#define handle_error(msg) \do { perror(msg); exit(EXIT_FAILURE); } while (0)void wait_handler(const asio::error_code& error){if (!error){// Wait succeeded.}}uint64_t value{0};
uint64_t total{0};int efd;void read_from_stream(asio::posix::stream_descriptor& stream) {stream.async_wait(asio::posix::stream_descriptor::wait_read,[&stream] (std::error_code ec) {int ret = read(efd, &value, sizeof(uint64_t));if (ret != 8)handle_error("[producer] failed to write eventfd");total += value;std::cout << std::this_thread::get_id() << " read " << value << " total " << total << std::endl;read_from_stream(stream);});
}int main() {auto start = std::chrono::steady_clock::now();std::cout << std::this_thread::get_id() << " main thread" << std::endl;efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);if (efd == -1)handle_error("eventfd");asio::io_context io_context;asio::posix::stream_descriptor stream{io_context, efd};read_from_stream(stream);std::thread thread([fd = efd, &start](){uint64_t one{1};for(uint64_t i = 0; i < 1000; i++){//std::cout << i << " write\n";int ret = write(fd, &one, sizeof(uint64_t));if (ret != 8)handle_error("[producer] failed to write eventfd");// std::this_thread::sleep_for(std::chrono::milliseconds(1));}auto diff = std::chrono::steady_clock::now() - start;std::cout << std::chrono::duration_cast<std::chrono::microseconds>(diff).count() << " \n";std::exit(0);});io_context.run();thread.join();return 0;
}

http://www.lryc.cn/news/298152.html

相关文章:

  • 《统计学简易速速上手小册》第9章:统计学在现代科技中的应用(2024 最新版)
  • 问题排查利器 - 分布式 trace
  • C++进阶(十四)智能指针
  • GPT最新进展:推出视频功能!迭代即将来临!
  • 各款Excel、word在线预览工具对比分析以及onlyoffice预览Excel加载时间长的解决方案
  • 【课程作业_01】国科大2023模式识别与机器学习实践作业
  • LeetCode374. Guess Number Higher or Lower——二分查找
  • 继承
  • 北斗卫星在物联网时代的应用探索
  • SQL注入 - 利用报错函数 floor 带回回显
  • NLP_Bag-Of-Words(词袋模型)
  • C语言rand随机数知识解析和猜数字小游戏
  • django中的缓存功能
  • 三、搜索与图论
  • 【翻译】Processing安卓模式的安装使用及打包发布(内含中文版截图)
  • MATLAB图像处理——边缘检测及图像分割算法
  • 探索设计模式:原型模式深入解析
  • IAR报错解决:Fatal Error[Pe1696]: cannot open source file “zcl_ha.h“
  • Qt网络编程-ZMQ的使用
  • 如何清理Docker占用的磁盘空间?
  • 从零开始学HCIA之NAT基本工作原理
  • Day40- 动态规划part08
  • 论文笔记:相似感知的多模态假新闻检测
  • 5G技术对物联网的影响
  • Nacos1.X源码解读(待完善)
  • 算法之双指针系列1
  • 苍穹外卖面试题
  • 【Qt 学习之路】在 Qt 使用 ZeroMQ
  • CI/CD到底是啥?持续集成/持续部署概念解释
  • golang常用库之-disintegration/imaging图片操作(生成缩略图)