|
std::cout << "boost库的网络编程asio(每隔固定时间干活)" << endl;
// 用到的技术点:asio io_service async_wait boost::bind expires_at
- #include <iostream>
- #include <boost/asio.hpp>
- #include <boost/bind.hpp>
- #include <boost/date_time/posix_time/posix_time.hpp>
- using namespace std;
- void print(const boost::system::error_code&, boost::asio::deadline_timer *t, int *count){
- if(*count < 5){
- std::cout << "次数:" << *count << std::endl;
- ++(*count);
- t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
- // 有了lambda函数后不推荐用bind了
- //"boost" 没有成员 "bind 要引入:#include <boost/bind.hpp>
- t->async_wait(boost::bind(print, boost::asio::placeholders::error, t, count));
- }
- }
- void callback(const boost::system::error_code&){
- std::cout << "1秒后干的事情!" << endl;
- }
- void async_call(){
- int count=0;
- boost::asio::io_service io;
- // 异步调用模式下:可以注册多个事件 循环调用 多次重复
- // 事件的注册 1
- boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
- // t.async_wait(callback);
- t.async_wait(boost::bind(print, boost::asio::placeholders::error, &t, &count));
-
- std::cout << "直接到这,不阻塞" << endl;
- io.run(); // 阻塞是在run里的,run()相当于一个while循环 结束条件:1、io.stop() 2、没有事件了
- std::cout << "最终的结果:" << count << std::endl;
-
- }
- int main(){
- //target_link_libraries(main -lboost_system)
- std::cout << "boost库的网络编程asio(每隔固定时间干活)" << endl;
- // 用到的技术点:asio io_service async_wait boost::bind expires_at
- async_call();
- return 0;
- }
复制代码
不用boost::bind,而用lambda函数在编译的时候会内联展开 效率比function要高
- #include <iostream>
- #include <boost/asio.hpp>
- #include <boost/date_time/posix_time/posix_time.hpp>
- using namespace std;
- void print(const boost::system::error_code&, boost::asio::deadline_timer& t, int& count){
- if(count < 5){
- std::cout << "次数:" << count << std::endl;
- ++count;
- t.expires_at(t.expires_at() + boost::posix_time::seconds(1));
- // 有了lambda函数后不推荐用bind了
- t.async_wait([&t, &count](const auto& error){
- print(error, t, count);
- });
- }
- }
- void callback(const boost::system::error_code&){
- std::cout << "1秒后干的事情!" << endl;
- }
- void async_call(){
- int count=0;
- boost::asio::io_service io;
- // 异步调用模式下:可以注册多个事件 循环调用 多次重复
- // 事件的注册 1
- boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
- // t.async_wait(callback);
- // t.async_wait(boost::bind(print, boost::asio::placeholders::error, &t, &count));
- // 不用boost::bind,而用lambda函数在编译的时候会内联展开 效率比function要高
- t.async_wait([&t, &count](const auto& error){
- print(error, t, count);
- });
-
- std::cout << "直接到这,不阻塞" << endl;
- io.run(); // 阻塞是在run里的,run()相当于一个while循环 结束条件:1、io.stop() 2、没有事件了
- std::cout << "最终的结果:" << count << std::endl;
-
- }
- int main(){
- //target_link_libraries(main -lboost_system)
- std::cout << "boost库的网络编程asio(每隔固定时间干活)不用boost::bind" << endl;
- // 用到的技术点:asio io_service async_wait boost::bind expires_at
- async_call();
- return 0;
- }
复制代码
|
|