Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio internal threads

When using boost::asio for some asynchronous TCP communication I noticed it starts a lot of (3-4) internal threads. Reading in the documentation, it says

"The implementation of this library for a particular platform may 
 make use of one or more internal threads to emulate asynchronicity"

Now my lib has very strict requirements to not start any extra threads (except one that is supplied by the client and which now starts io_service::run()). Is there any way to stop boost::asio from creating these extra threads?

Alternatively, is there any other async library out there that can run in only one thread?

like image 571
Rolle Avatar asked Feb 20 '13 13:02

Rolle


People also ask

Does Boost asio use threads?

If the run() method is called on an object of type boost::asio::io_service, the associated handlers are invoked on the same thread. By using multiple threads, an application can call multiple run() methods simultaneously.

What is Boost asio Strand?

The boost::asio::bind_executor() function is a helper to bind a specific executor object, such as a strand, to a completion handler. This binding automatically associates an executor as shown above. For example, to bind a strand to a completion handler we would simply write: my_socket.

What is Boost :: asio :: Io_service?

Asio defines boost::asio::io_service , a single class for an I/O service object. Every program based on Boost. Asio uses an object of type boost::asio::io_service . This can also be a global variable. While there is only one class for an I/O service object, several classes for I/O objects exist.

Is Boost asio header only?

By default, Boost. Asio is a header-only library. However, some developers may prefer to build Boost. Asio using separately compiled source code.


1 Answers

You can disable the emulated asynchronous operation support by defining BOOST_ASIO_DISABLE_THREADS in the appropriate translation units. The documentation has this to say about the definition

Explicitly disables Boost.Asio's threading support, independent of whether or not Boost as a whole supports threads.

If you didn't find the platform specific implementation notes, it clearly states which operations use this emulation. For example I know on nearly every platform async_resolve() is emulated in this fashion, the thread is created upon the first invocation of async_resolve(). Some (all?) Windows platforms emulate several other operations such as deadline_timer operations.

One alternative to disabling threading support might be to avoid these emulated operations. I personally have not used BOOST_ASIO_DISABLE_THREADS in a project so I'm unsure if it has other side effects.

like image 85
Sam Miller Avatar answered Sep 30 '22 00:09

Sam Miller