我试图为std :: thread的向量构建一个简单的封装;我想初始化最多MAX个线程。如果我达到最大数量,主线程将运行代码(写入输出文件)。 我保留了一个包含std :: thread和bool标志的类的Vector。我没有直接通过std :: threads构造函数运行函数,而是发送一个包装器函数来改变布尔标志,所以我可以检查一个线程是否已经完成,如果没有,继续运行(如果已完成,请加入并关闭它)。 包装器的我的代码:
#include <thread>
class RvThread {
bool is_running;
std:thread this_thread;
template <typename F, typename ... Args>
static void function_wrapper(bool* flag, F &&function, Args&& ... args) {
function(args...);
*is_running = false;
}
public:
template <typename F, typename ... Args>
RvThread(F &&function, Args&& ... args) : is_running(true), this_thread(RvThread::function_wrapper<F, Args...>,&is_running,function, args...) {}
~RvThread(){
join();
}
void join () {
this_thread.join();
}
bool is_done() {
return !is_running;
}
};
template <unsigned char max_threads>
class Threads {
unsigned char num_active;
std::vector<RvThread> running_threads;
void join_done(){
for (auto &it : running_threads) {
if (it->is_done()) {
running_threads.remove(it);
num_active--;
}
}
}
public:
Threads() : num_active(0) {}
template <typename F, typename ... Args>
void run(F&& function, Args&& ... args) {
join_done();
if (num_active < max_threads) {
running_threads.push_back(RvThread(function, args...));
num_active++;
} else {
function(args...);
}
}
};
我尝试传递的功能是:
template<typename C>
inline void writeFile(const Path &filePath, const C &content, bool append) {
OutFile file(filePath, append);
for(auto it=content.begin(); it!=content.end(); it++) {
file.file << *it;
file.file << '\n';
}
}
template<>
inline void writeFile(const Path &filePath, const RvString &content, bool append) {
OutFile file(filePath, append);
file.file << content;
}
template<typename C>
void FileManager::writeRawFile(const Path &filePath, const C &content, bool append, bool FileMayBeRead) {
writeFile(filePath.is_absolute() ? filePath : baseDir/filePath, content, append);
auto it = sourceFiles.find(filePath.filename().string());
if (it != sourceFiles.end()) {
sourceFiles.erase(it);
}
if (FileMayBeRead && paths.find(filePath.filename().string())==paths.end()) {
paths.insert(make_pair(filePath.filename().string(), filePath));
}
}
template<typename C>
void FileManager::writeRawFile_t(Path filePath, C &&content, bool append, bool FileMayBeRead, bool run_thread) {
static Threads<8> WritingThreads;
if (run_thread) {
WritingThreads.run(writeFile, std::move(filePath.is_absolute() ? filePath : baseDir/filePath), std::move(content), std::move(append));
} else {
writeFile(filePath.is_absolute() ? filePath : baseDir/filePath, content, append);
} ...
我继续得到未解析的重载函数类型的错误,并且'class std :: result_of中没有名为'type'的类型