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 
#include 
#include 
#include 

#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(diff).count() << " \n";
    std::exit(0);
  });

  io_context.run();
  thread.join();

  return 0;
}

你可能感兴趣的:(c++,网络)