在这个博客中,我找到了一个非常巧妙的例子,说明如何使用boost :: asio创建一个简单的线程池.我基本上想要像这样使用它:
#include <thread>
#include <functional>
#include <boost/asio.hpp>
int main ( int argc, char* argv[] ) {
asio::io_service io_service;
asio::io_service::work work(io_service);
std::vector<std::thread> threadPool;
for(size_t t = 0; t < std::thread::hardware_concurrency(); t++){
threadPool.push_back(thread(std::bind(&asio::io_service::run, &io_service)));
}
io_service.post(std::bind(an_expensive_calculation, 42));
io_service.post(std::bind(a_long_running_task, 123));
//Do some things with the main thread
io_service.stop();
for(std::thread& t : threadPool) {
t.join();
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,Boost :: asio主要用于网络IO.但是,我主要想将它用于通用功能.将使用并发问题asio::io_service::strand.
所以我的问题:创建这样的线程池是一个好主意,即使我的程序不使用网络IO?与其他线程池实现相比,是否存在明显的性能损失?如果是这样,那么还有更好的实现吗?
我想使用一个用于GUI的线程和一个用于某个套接字IO的工作线程来实现Boost Asio模式.
工作线程将用于boost::asio::io_service管理套接字客户端.套接字上的所有操作仅由工作线程执行.
GUI线程需要从工作线程发送和接收消息.
我无法确定如何使用Boost Asio实现此模式.
我已经用标准的Asio方式实现了套接字通信(我io_service.run()从工作线程调用并使用async_read_some/ async_send).我不需要strands因为io_service.run()只是从工作线程调用.
现在我正在尝试添加跨线程消息队列.我该如何实施呢?
我应该run在io_service从GUI线程呢?
或者我应该使用strandswith post将消息从GUI线程发布到工作线程(不调用io_service.run()或io_service.poll_one()从GUI线程),并使用操作系统的GUI消息循环将消息从工作线程发布到GUI线程?
如果我还需要调用io_service.run()或io_service.poll_one()从GUI线程调用,我是否需要strands在套接字操作上使用,因为它io_service是在两个线程之间共享的?
编辑:为了澄清我的问题,我想尽我所能,使用Boost Asio来实现消息队列,只有当Boost Asio无法完成工作时才依赖其他库.