在 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中文網其他相關文章!