Home >Backend Development >C++ >How do I create a thread pool using Boost in C ?
In C , creating a thread pool using the Boost library requires a straightforward process.
Firstly, instantiate an asio::io_service and a thread_group. Subsequently, populate the thread_group with threads connected to the io_service. Tasks can then be assigned to the threads utilizing the boost::bind function.
To halt the threads, simply discontinue the io_service and combine all of them.
The necessary header files are:
#include <boost/asio/io_service.hpp> #include <boost/bind.hpp> #include <boost/thread/thread.hpp>
An example implementation is provided below:
// Establish an io_service and a thread_group (essentially a pool) boost::asio::io_service ioService; boost::thread_group threadpool; // Commence ioService processing loop boost::asio::io_service::work work(ioService); // Add threads to pool (e.g., two in this case) threadpool.create_thread( boost::bind(&boost::asio::io_service::run, &ioService) ); threadpool.create_thread( boost::bind(&boost::asio::io_service::run, &ioService) ); // Assign tasks to thread pool via ioService.post() // Refer to "http://www.boost.org/doc/libs/1_54_0/libs/bind/bind.html#with_functions" for details on boost::bind ioService.post(boost::bind(myTask, "Hello World!")); ioService.post(boost::bind(clearCache, "./cache")); ioService.post(boost::bind(getSocialUpdates, "twitter,gmail,facebook,tumblr,reddit")); // Halt ioService processing loop (no new tasks will execute after this point) ioService.stop(); // Wait and combine threads in thread pool threadpool.join_all();
(Source: Recipes < Asio)
The above is the detailed content of How do I create a thread pool using Boost in C ?. For more information, please follow other related articles on the PHP Chinese website!