gpt4 book ai didi

线程池的 C++ std::thread 停止条件

转载 作者:行者123 更新时间:2023-11-28 07:59:04 28 4
gpt4 key购买 nike

我正在编写一个程序,该程序利用线程池来搜索指定扩展名的文件以匹配正则表达式。

我的线程池是这样的:

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 中的所有项目都已完成,然后再加入线程。任何想法都将不胜感激。

最佳答案

我建议有一个线程(可能是生成文件处理线程的同一个线程)专用于递归文件系统搜索匹配文件;它可以将文件添加到工作队列中,文件搜索线程可以从该工作队列中获取工作。您可以使用条件变量来协调这一点。

如您所见,协调关闭有点棘手。文件系统搜索线程完成搜索后,它可以设置一些对工作线程可见的“刚刚完成排队的内容”标志,然后向它们发出信号以唤醒并尝试处理另一个文件:如果它们发现文件/工作队列为空他们退出。文件系统搜索线程然后加入所有工作线程。

关于线程池的 C++ std::thread 停止条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979945/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com