我正在编写一个程序,该程序利用线程池来搜索指定扩展名的文件以匹配正则表达式。
我的线程池如下所示:
for( int i = 0; i < _nThreads; ++i )
{
_threads.push_back( thread( &ThreadPool::GrepFunc, this ) );
}
运行函数如下所示:
void ThreadPool::GrepFunc()
{
// implement a barrier
while( !_done )
{
while( !_tasks.empty() )
{
fs::path task;
bool gotTask = false;
{
lock_guard<mutex> tl( _taskMutex );
if( !_tasks.empty() )
{
task = _tasks.front();
_tasks.pop();
gotTask = true;
}
}
if( gotTask )
{
if( std::tr2::sys::is_directory( task ) )
{
for( fs::directory_iterator dirIter( task ), endIter; dirIter != endIter; ++dirIter )
{
if( fs::is_directory( dirIter->path() ) )
{
{ lock_guard<mutex> tl( _taskMutex );
_tasks.push( dirIter->path() ); }
}
else
{
for( auto& e : _args.extensions() )
{
if( !dirIter->path().extension().compare( e ) )
{
SearchFile( dirIter->path() );
}
}
}
}
}
else
{
for( auto& e : _args.extensions() )
{
if( !task.extension().compare( e ) )
{
SearchFile( task );
}
}
}
}
}
}
}
本质上,该程序从用户那里接收一个初始目录,并将递归地搜索它和所有子目录以查找与扩展名匹配的文件,以寻找正则表达式匹配。我无法弄清楚如何确定何时达到 _done 的停止情况。我需要确保初始目录中的所有目录和文件都已被扫描,并且在我重新加入线程之前,_tasks 中的所有项目都已完成。任何想法都会非常感激。