【发布时间】:2016-12-20 05:14:47
【问题描述】:
我正在开发一个程序,该程序从搜索文件系统的多个线程打印正则表达式匹配,每个线程将其 id 添加到队列并通知主线程有一些线程要从线程池中删除,这是一个标准: :向量。
此时,每当我执行时,我都会解锁和锁定互斥锁 对要保护的资源的操作。感觉就像我在 想到这一切都错了,而且我太细化了。将 最好在进入while循环之前锁定互斥锁,解锁 它在弹出队列之后,然后在之前再次锁定它 !finished_threads.empty() 在下一次迭代中被调用?
void RegexSearch::Run()
{
running = true;
search_pool.push_back(std::thread([&] { StartPrint(); }));
/*
Get directories and create another thread for each subdirectory while there are
less threads than maximum in the pool.
*/
fs::path searchDir(directory);
for (const auto& dir : searchDir)
{
if (search_pool.size() >= MAX_THREADS)
{
std::unique_lock<std::mutex> lck(mu, std::defer_lock);
// Wait to be notified that thread is finished execution and another can start.
max_thread_cond.wait(lck);
lck.lock();
while (!finished_threads.empty())
{
lck.unlock();
lck.lock();
std::thread::id remove_thread = finished_threads.front();
lck.unlock();
lck.lock();
finished_threads.pop();
lck.unlock();
std::remove_if(search_pool.begin(), search_pool.end(), [&remove_thread](const std::thread::id &t) { return remove_thread == t; });
lck.lock();
}
}
}
}
【问题讨论】:
标签: c++ multithreading threadpool