用lambda函数改写std::asio的例子程序
Posted litandy2016
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用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& io) : strand_(io), timer1_(io, asio::chrono::seconds(1)), timer2_(io, asio::chrono::seconds(1)), count_(0) do_callback1(); do_callback2(); ~StrandCallback() std::cout << "Final count is " << count_ << std::endl; void do_callback1() timer1_.async_wait( asio::bind_executor(strand_, [this](const asio::error_code& ec) if (count_ < 10) std::cout << "Timer 1: " << count_ << std::endl; ++count_; timer1_.expires_at(timer1_.expiry() + asio::chrono::seconds(3)); do_callback1(); ) ); void do_callback2() timer2_.async_wait( asio::bind_executor(strand_, [this](const asio::error_code& ec) if (count_ < 10) std::cout << "Timer 2: " << count_ << std::endl; ++count_; timer2_.expires_at(timer2_.expiry() + asio::chrono::seconds(2)); do_callback2(); ) ); private: 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); // 场景2 //Callback c(io); // 场景3 StrandCallback sc(io); io.run(); return 0;
以上是关于用lambda函数改写std::asio的例子程序的主要内容,如果未能解决你的问题,请参考以下文章
python中的zipmapreduce lambda函数的使用。