在 C 语言中,使用 Boost 库创建线程池需要一个简单的过程。
首先,实例化一个 asio::io_service 和一个 thread_group。随后,使用连接到 io_service 的线程填充 thread_group。然后可以利用 boost::bind 函数将任务分配给线程。
要停止线程,只需停止 io_service 并将所有线程组合起来即可。
必要的头文件是:
#include <boost/asio/io_service.hpp> #include <boost/bind.hpp> #include <boost/thread/thread.hpp>
下面提供了一个示例实现:
// 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();
(来源:Recipes
)阿西奥)以上是如何在 C 中使用 Boost 创建线程池?的详细内容。更多信息请关注PHP中文网其他相关文章!