我认为你想要做的事情非常好,假设你的IO操作足够复杂,以便降低异步实现的开销。我简单的建议是这样的(从旧question复制):
#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以确保并行处理 并未调用特定文件。
谢谢。我正在使用VS2010 ...如果我理解正确,无论是编写同步还是异步,io_operation都是一样的?只有来电者决定如何使用它?此外,如果多个线程可以写入相同的文件...我必须使用某种锁?但是,如果每个线程都使用不同的文件路径调用函数 - 多线程仍可能写入同一个文件吗? – Thalia
@Thalia:是的,操作与没有异步操作时使用的操作相同。如果每个线程都使用不同的文件路径调用该函数,那么您将不会收到我假设的任何错误。确保你必须使用某种锁。链接我在我的帖子是通常的方式来做这个提升asio(看看参考和例子)。但是,如果您愿意,也可以在'io_operation'函数中使用'std :: mutex'。 – Haatschii
你有没有把这段代码放入编译器? –