前言
上一篇简单介绍了Asio的同步和异步原理图,这篇接着介绍Asio的简单示例。
使用成员函数作为回调函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <iostream> #include <boost/asio.hpp> #include <boost/bind/bind.hpp>
class printer { public: printer(boost::asio::io_context& io) : timer_(io, boost::asio::chrono::seconds(1)), count_(0) { timer_.async_wait(boost::bind(&printer::print, this)); }
~printer() { std::cout << "Final count is " << count_ << std::endl; }
void print() { if (count_ < 5) { std::cout << count_ << std::endl; ++count_; timer_.expires_at(timer_.expiry() + boost::asio::chrono::seconds(1)); timer_.async_wait(boost::bind(&printer::print, this)); } }
private: boost::asio::steady_timer timer_; int count_; };
int main() { boost::asio::io_context io; printer p(io); io.run();
return 0; }
|
可以看到回调函数并没有使用静态全局函数而是成员函数,同时回调函数的参数是this指针。
这里涉及到C++的内存分布,类的成员函数都是在一块内存中,每实例化一个对象并不需要分配内存给函数,而是复用类的成员函数,区别在于类的成员函数有一个隐藏的参数(对象指针)。类的成员函数会根据对象指针自动处理函数。
多线程回调函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <iostream> #include <boost/asio.hpp> #include <boost/thread/thread.hpp> #include <boost/bind/bind.hpp>
class printer { public: printer(boost::asio::io_context& io) : strand_(boost::asio::make_strand(io)), timer1_(io, boost::asio::chrono::seconds(1)), timer2_(io, boost::asio::chrono::seconds(1)), count_(0) { timer1_.async_wait(boost::asio::bind_executor(strand_, boost::bind(&printer::print1, this))); timer2_.async_wait(boost::asio::bind_executor(strand_, boost::bind(&printer::print2, this))); }
~printer() { std::cout << "Final count is " << count_ << std::endl; }
void print1() { if (count_ < 10) { std::cout << "Timer 1: " << count_ << std::endl; ++count_; timer1_.expires_at(timer1_.expiry() + boost::asio::chrono::seconds(1)); timer1_.async_wait(boost::asio::bind_executor(strand_, boost::bind(&printer::print1, this))); } }
void print2() { if (count_ < 10) { std::cout << "Timer 2: " << count_ << std::endl; ++count_; timer2_.expires_at(timer2_.expiry() + boost::asio::chrono::seconds(1)); timer2_.async_wait(boost::asio::bind_executor(strand_, boost::bind(&printer::print2, this))); } }
private: boost::asio::strand<boost::asio::io_context::executor_type> strand_; boost::asio::steady_timer timer1_; boost::asio::steady_timer timer2_; int count_; };
int main() { boost::asio::io_context io; printer p(io); boost::thread t(boost::bind(&boost::asio::io_context::run, &io));
t.detach(); std::cout << "aaaa"<< std::endl; while (1) { Sleep(500);
} return 0; }
|
结束
Asio的简单应用就到这里,下篇介绍Asio实现网络通信。