用lambda函数改写std::asio的例子程序

#include "stdafx.h"

#define ASIO_STANDALONE

#include <iostream>
#include <asio.hpp>

void do_callback(asio::steady_timer& timer, int& count)
{
  timer.async_wait(
    [&](const asio::error_code& ec){
      if (count < 5){
        std::cout << count << std::endl;
        ++(count);

        timer.expires_at(timer.expiry() + asio::chrono::seconds(1));
        do_callback(timer, count);
      }else{
        std::cout << "Final count is " << count << std::endl;
      }
    }
  );
}

class Callback
{
public:
  Callback(asio::io_context& io)
    : timer_(io, asio::chrono::seconds(1)),
    count_(0)
  {
  do_callback();
  }

  ~Callback()
  {
    std::cout << "Final count is " << count_ << std::endl;
  }

  void do_callback()
  {
    timer_.async_wait(
      [this](const asio::error_code& ec){
        if (count_ < 5){
          std::cout << count_ << std::endl;
          ++(count_);

          timer_.expires_at(timer_.expiry() + asio::chrono::seconds(1));
          do_callback();
        }
      }
    );
  }
private:
  asio::steady_timer timer_;
  int count_;
};

class StrandCallback
{
public:
  StrandCallback(asio::io_context* pio)
    : pio_(pio), strand_(*pio),
    timer1_(*pio, asio::chrono::seconds(1)),
    timer2_(*pio, asio::chrono::seconds(1)),
    count_(0)
  {
  }

  ~StrandCallback()
  {
    std::cout << "Final count is " << count_ << std::endl;
  }

  void go()
  {
    do_callback(timer1_, 1, 2);
    do_callback(timer2_, 2, 3);

    asio::thread t1(std::bind(&StrandCallback::thread_fun, this, pio_));
    asio::thread t2(std::bind(&StrandCallback::thread_fun, this, pio_));

    t1.join();
    t2.join();
  }

  void thread_fun(asio::io_context* pio)
  {
    pio->run();
  }

  void do_callback(asio::steady_timer& timer, int iTag, int iWait)
  {
    timer.async_wait(
      asio::bind_executor(strand_,
        [=, &timer](const asio::error_code& ec){
          if (count_ < 20){
            std::cout << "Timer " << iTag << ":"<< count_ << std::endl;
            ++count_;

            timer.expires_at(timer.expiry() + asio::chrono::seconds(iWait));

            do_callback(timer, iTag, iWait);
          }
        }
      )
    );
  }

private:
  asio::io_context* pio_;
  asio::io_context::strand strand_;
  asio::steady_timer timer1_;
  asio::steady_timer timer2_;
  int count_;
};

int _tmain(int argc, _TCHAR* argv[])
{
  asio::io_context io;

  // 场景1
  //int count = 0;
  //asio::steady_timer t(io, asio::chrono::seconds(1));
  //do_callback(t, count);
  //io.run();

  // 场景2
  //Callback c(io);
  //io.run();

  // 场景3
  StrandCallback sc(&io);
  sc.go();

  return 0;
}

posted on 2019-08-21 09:04  litandy  阅读(513)  评论(0编辑  收藏  举报

导航