使用 C 中的 Boost 创建和使用线程池
要使用 C 中的 Boost 建立线程池,请遵循以下步骤:
boost::asio::io_service ioService; boost::thread_group threadpool;
threadpool.create_thread( boost::bind(&boost::asio::io_service::run, &ioService) );
ioService.post(boost::bind(myTask, "Hello World!"));
停止线程(通常在程序终止时):
ioService.stop();
threadpool.join_all();
示例代码:
// Create io_service and thread_group boost::asio::io_service ioService; boost::thread_group threadpool; // Start the ioService processing loop boost::asio::io_service::work work(ioService); // Add threads to the thread pool 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 the thread pool ioService.post(boost::bind(myTask, "Hello World!")); ioService.post(boost::bind(clearCache, "./cache")); ioService.post(boost::bind(getSocialUpdates, "twitter,gmail,facebook,tumblr,reddit")); // Stop the ioService processing loop ioService.stop(); // Join all threads in the thread pool threadpool.join_all();
在总之,Boost 提供了一种简单的机制来创建线程池并向其分配任务,从而在 C 应用程序中实现并发执行。
以上是如何在 C 中创建和使用带有 Boost 的线程池?的详细内容。更多信息请关注PHP中文网其他相关文章!