Tips and Tricks

Consider using std::vector<> for buffers over raw arrays and boost::array

A buffer variable for use with read and write operations could be defined:

  char buffer[max_size];


  boost::array<char, max_size> buffer;


  std::vector<char> buffer(max_size);

Consider using this last form based on std::vector<>, as it allows your application to use buffer debugging.

Repeating timers

Asio has a rather good deadline timer, but try using it as a repeating timer and you will come into difficulties when attempting to cancel it.

This is an interesting example of an implementaion of a repeating timer which is basd on the basic_deadline_timer and uses its implementaion and service to acheive a safe repeating time which is cancellable. This timer provides a guarante that the async callback will not be invoked when the cancel returns.

"Stopping the io_service from running out-of-work" continued.

In addition to the great Boost.Asio docs consider combining boost::asio::io_service::work with boost::optional:

boost::optional<io_service::work> work_io_service_guard(
boost::thread_group work_threads;
for (std::size_t i = 0; i != work_thread_count; ++i)
      boost::bind(&io_service::run, boost::ref(work_io_service)));
// add some work for work_io_service
work_io_service_guard = boost::none;

It's more lightweight than using std::auto_ptr - it uses stack instead of heap to allocate io_service::work instance.

If you would like to remain boost- free and have a c++14 compiler available, you can use std::experimental::optional:

std::experimental::optional<asio::io_service::work> work_io_service_guard(
std::vector<std::thread> threads;
for (unsigned int i = 0; i < work_thread_count; ++i) {
    threads.emplace_back([&]() {; }); 
// add some work for work_io_service 
work_io_service_guard = std::experimental::nullopt; 
    [](auto& thread ){ thread.join(); } );
Topic revision: r7 - 26 May 2014 - 19:05:40 - MatthewAveryUsa?
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback