我认为你想要做的非常好,假设你的 IO 操作足够复杂,以证明异步实现的开销。我的简单建议看起来像这样(从一个旧问题复制):
#include <thread>
#include <functional>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
void io_operation(int parameter) {
//Your stuff
}
int main ( int argc, char* argv[] ) {
boost::asio::io_service io_service;
boost::asio::io_service::work work(io_service);
//Set up a thread pool taking asynchronically care of your orders
std::vector<std::thread> threadPool;
for(size_t t = 0; t < std::thread::hardware_concurrency(); t++){
threadPool.push_back(std::thread(boost::bind(&boost::asio::io_service::run, &io_service)));
}
//Post an IO-operation
io_service.post(std::bind(io_operation, 123));
//Join all threads at the end
io_service.stop();
for(std::thread& t : threadPool) {
t.join();
}
}
这假设您可以使用C++11
线程。您还应该知道,这并不能确保只有一个线程正在写入特定文件。因此,您可能需要使用strands来确保对特定文件的调用不会并行处理。