Boost asio 定时器

本文详细介绍了Boost ASIO库中的定时器使用,包括同步和异步计时器的实现,以及如何绑定参数和使用成员函数作为handler。通过实例展示了多线程环境下同步Handlers的运用,同时给出了TCP daytime客户端和服务端的同步和异步实现。
摘要由CSDN通过智能技术生成

 

Boost asio入门学习笔记

 

 版权声明:本文为博主原创文章,未经博主允许不得转载。文章中有连接失效或是技术谬误的地方,请与我联系。 https://blog.csdn.net/luchengtao11/article/details/82996126

Timer1:使用一个同步计时器

 
  1. #include <iostream>

  2. #include "boost/asio.hpp"

  3.  
  4.  
  5. int main()

  6. {

  7. boost::asio::io_context io;

  8. boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));

  9. t.wait();

  10. std::cout << "Hello,world!" << std::endl;

  11.  
  12. return 0;

  13. }

所谓的同步,就是指t.wait必须等待五秒才会向下执行。 

 

Timer2:使用一个异步计时器

 
  1. #include <iostream>

  2. #include "boost/asio.hpp"

  3.  
  4.  
  5. void print(const boost::system::error_code&)

  6. {

  7. std::cout << "Hello world!" << std::endl;

  8. }

  9. int main()

  10. {

  11. boost::asio::io_context io;

  12. boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));

  13. t.async_wait(&print);

  14. std::cout << "Hehe!" << std::endl;

  15. io.run();

  16. return 0;

  17. }

异步是指:上述程序并不会在t.async_wait(&print)处阻塞,而是继续运行,等到计时器计满5秒,才会调用print。上述程序的运行结果就是,先输出Hehe,再输出Hello world!。

Timer3:为handle绑定参数

 
  1. #include <iostream>

  2. #include "boost/asio.hpp"

  3. #include "boost/bind.hpp"

  4.  
  5.  
  6. void print(const boost::system::error_code&,boost::asio::steady_timer *t,int *count)

  7. {

  8. if (*count < 5)

  9. {

  10. std::cout << *count << std::endl;

  11. ++(*count);

  12. t->expires_at(t->expiry() + boost::asio::chrono::seconds(1));//设置新的过期时间

  13. t->async_wait(boost::bind(print, boost::asio::placeholders::error, t, count));//为print邦定参数,转换为函数对象

  14. }

  15. }

  16. int main()

  17. {

  18. boost::asio::io_context io;

  19. int count = 0;

  20. boost::asio::steady_timer t(io, boost::asio::chrono::seconds(1));

  21. t.async_wait(boost::bind(print,boost::asio::placeholders::error,&t,&count));

  22. io.run();

  23. std::cout << "Final count is " << count << std::endl;

  24. return 0;

  25. }

Timer4:使用一个成员函数作为handler

 
  1. #include <iostream>

  2. #include "boost/asio.hpp"

  3. #include "boost/bind.hpp"

  4.  
  5.  
  6. class printer

  7. {

  8. public:

  9. printer(boost::asio::io_context& io)

  10. :timer_(io, boost::asio::chrono::seconds(1)),

  11. count_(0)

  12. {

  13. timer_.async_wait(boost::bind(&printer::print, this));

  14. }

  15. ~printer()

  16. {

  17. std::cout << "Final count is " << count_ << std::endl;

  18. }

  19.  
  20. void print()

  21. {

  22. if (count_ < 5)

  23. {

  24. std::cout << count_ << std::endl;

  25. ++count_;

  26.  
  27. timer_.expires_at(timer_.expiry() + boost::asio::chrono::seconds(1));

  28. timer_.async_wait(boost::bind(&printer::print, this));

  29. }

  30.  
  31. }

  32. private:

  33. boost::asio::steady_timer timer_;

  34. int count_;

  35. };

  36. int main()

  37. {

  38. boost::asio::io_context io;

  39. printer p(io);

  40. io.run();

  41.  
  42. return 0;

  43. }

与之前实例实现的功能一致,只不过更巧妙一些。the asio library provides a guarantee that callback handlers will only be called from threads that are currently calling io_context::run(). Consequently, calling io_context::run() from only one thread ensures that callback handlers cannot run concurrently.即,回调函数只能被一个线程调用,不能并行。

单线程有以下局限:

  • 如果handle非常耗时,将会造成可怜的响应速度。
  • 不能针对多核处理器进行扩展优化。

Timer5:多线程的同步Handlers

 
  1. #include <iostream>

  2. #include "boost/asio.hpp"

  3. #include "boost/thread/thread.hpp"

  4. #include "boost/bind.hpp"

  5.  
  6.  
  7. class printer

  8. {

  9. public:

  10. printer(boost::asio::io_context& io)

  11. :strand_(io),

  12. timer1_(io, boost::asio::chrono::seconds(1)),

  13. timer2_(io,boost::asio::chrono::seconds(1)),

  14. count_(0)

  15. {

  16. timer1_.async_wait(boost::asio::bind_executor(strand_, boost::bind(&printer::print1, this))); //邦定在同一个strand对象上的handler不能并发

  17. timer2_.async_wait(boost::asio::bind_executor(strand_, boost::bind(&printer::print2, this)));

  18.  
  19. }

  20. ~printer()

  21. {

  22. std::cout << "Final count is " << count_ << std::endl;

  23. }

  24.  
  25. void print1()

  26. {

  27. if(count_ < 10)

  28. {

  29. std::cout << "Timer 1: " << count_ << std::endl;

  30. ++count_;

  31.  
  32. timer1_.expires_at(timer1_.expiry() + boost::asio::chrono::seconds(1));

  33.  
  34. timer1_.async_wait(boost::asio::bind_executor(strand_,

  35. boost::bind(&printer::print1, this)));

  36. }

  37.  
  38. }

  39.  
  40. void print2()

  41. {

  42. if (count_ < 10)

  43. {

  44. std::cout << "Timer 2: " << count_ << std::endl;

  45. ++count_;

  46.  
  47. timer2_.expires_at(timer2_.expiry() + boost::asio::chrono::seconds(1));

  48.  
  49. timer2_.async_wait(boost::asio::bind_executor(strand_,

  50. boost::bind(&printer::print2, this)));

  51. }

  52. }

  53.  
  54. private:

  55. boost::asio::io_context::strand strand_;

  56. boost::asio::steady_timer timer1_;

  57. boost::asio::steady_timer timer2_;

  58. int count_;

  59. };

  60. int main()

  61. {

  62. boost::asio::io_context io;

  63. printer p(io);

  64. boost::thread t(boost::bind(&boost::asio::io_context::run, &io));

  65. io.run();

  66. t.join();//等待子线程运行完毕

  67.  
  68.  
  69. return 0;

  70. }

daytime1:实现一个同步的TCP daytime客户端

 
  1. #include <iostream>

  2. #include<boost/array.hpp>

  3. #include "boost/asio.hpp"

  4.  
  5. using boost::asio::ip::tcp;

  6.  
  7. int main(int argc,char * argv[])

  8. {

  9. try

  10. {

  11.  
  12. boost::asio::io_context io_context; //All programs that use asio need to have at least one io_context object.

  13. tcp::resolver resolver(io_context);

  14.  
  15. std::string host = "127.0.0.1";//specify the host

  16. //resolver需要一个query对象,并将query转换为a list of endpoints

  17. //host name,也就是IP地址

  18. //the name of service,也就是端口...

  19. tcp::resolver::query query(tcp::v4(), host, "13");

  20. // tcp::resolver::query query(tcp::v4(),argv[1], "13");

  21.  
  22.  
  23. tcp::resolver::results_type endpoints = resolver.resolve(query);

  24.  
  25. tcp::socket socket(io_context);

  26. boost::asio::connect(socket, endpoints);

  27.  
  28. for (;;)

  29. {

  30. boost::array<char, 128>buf;

  31. boost::system::error_code error;

  32.  
  33. size_t len = socket.read_some(boost::asio::buffer(buf), error);

  34.  
  35. if (error == boost::asio::error::eof)

  36. {

  37. break;//连接关闭

  38. }

  39. else if (error)

  40. {

  41. throw boost::system::system_error(error);

  42. }

  43.  
  44. std::cout.write(buf.data(), len);

  45. }

  46. }

  47. catch (const std::exception& e)

  48. {

  49. std::cerr << e.what() << std::endl;

  50. }

  51.  
  52. return 0;

  53. }

daytime2:实现一个同步的TCP daytime 服务端

 
  1. #include <ctime>

  2. #include <iostream>

  3. #include <string>

  4. #include <boost/asio.hpp>

  5.  
  6. using boost::asio::ip::tcp;

  7.  
  8. std::string make_daytime_string()

  9. {

  10. using namespace std;

  11. time_t now = time(0);

  12. return ctime(&now);

  13. }

  14.  
  15.  
  16. int main()

  17. {

  18. try

  19. {

  20. boost::asio::io_context io_context;

  21. tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 13));

  22.  
  23. for (;;)

  24. {

  25. tcp::socket socket(io_context);

  26. acceptor.accept(socket);

  27. std::string message = make_daytime_string();

  28. boost::system::error_code igored_error;

  29. boost::asio::write(socket, boost::asio::buffer(message), igored_error);

  30. }

  31. }

  32. catch (const std::exception& e)

  33. {

  34. std::cerr << e.what() << std::endl;

  35. }

  36. }

daytime3:一个异步tcp daytime的服务端

 
  1. #include <ctime>

  2. #include <iostream>

  3. #include <string>

  4. #include <boost/asio.hpp>

  5. #include <boost/enable_shared_from_this.hpp>

  6. #include <boost/bind.hpp>

  7.  
  8. using boost::asio::ip::tcp;

  9.  
  10. std::string make_daytime_string()

  11. {

  12. using namespace std;

  13. time_t now = time(0);

  14. return ctime(&now);

  15. }

  16.  
  17. class tcp_connection :public boost::enable_shared_from_this<tcp_connection>

  18. {

  19. public:

  20. typedef boost::shared_ptr<tcp_connection> pointer;

  21.  
  22. static pointer create(boost::asio::io_context&io_context)

  23. {

  24. return pointer(new tcp_connection(io_context));

  25. }

  26.  
  27. tcp::socket & socket()

  28. {

  29. return socket_;

  30. }

  31.  
  32. void start()

  33. {

  34. message_ = make_daytime_string();

  35. boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this(),

  36. boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

  37. }

  38.  
  39. private:

  40.  
  41. tcp_connection(boost::asio::io_context&io_context)

  42. :socket_(io_context)

  43. {

  44.  
  45. }

  46. void handle_write(const boost::system::error_code, size_t)

  47. {

  48.  
  49. }

  50. tcp::socket socket_;

  51. std::string message_;

  52. };

  53.  
  54.  
  55. class tcp_server

  56. {

  57. public:

  58. tcp_server(boost::asio::io_context&io_context)

  59. :acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))

  60. {

  61. start_accept();

  62. }

  63.  
  64. private:

  65.  
  66. void start_accept()

  67. {

  68. tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.get_executor().context());

  69. acceptor_.async_accept(new_connection->socket(), boost::bind(&tcp_server::handle_accept, this, new_connection, boost::asio::placeholders::error));

  70.  
  71. //此处不阻塞,直接返回,当有连接到达时,调用handle_accept

  72. }

  73.  
  74. void handle_accept(tcp_connection::pointer new_connection,

  75. const boost::system::error_code& error)

  76. {

  77. if (!error)

  78. {

  79. new_connection->start();

  80. }

  81.  
  82. start_accept();

  83. }

  84. tcp::acceptor acceptor_;

  85. };

  86.  
  87. int main()

  88. {

  89. try

  90. {

  91. boost::asio::io_context io_context;

  92. tcp_server server(io_context);

  93. io_context.run();

  94. }

  95. catch (const std::exception& e)

  96. {

  97. std::cerr << e.what() << std::endl;

  98. }

  99. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值