本文主要是介绍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;
}
这篇关于asio监听eventfd的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!