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

北城以北 提交于 2020-04-30 16:45:21

#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;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!