如何停止所有正在运行的线程并控制线程数?

时间:2019-08-19 21:56:39

标签: c++ multithreading

我与std:: thread一起工作,我必须创建一个多线程应用程序来搜索文件,当找到该文件时,它应该停止所有线程。我尝试为此使用std:terminate(),但此后我的程序因错误而停止。我也想问一下,如何控制函数使用的线程数? 我的代码:

#include <iostream>
#include  <conio.h>
#include <string>  
#include <experimental/filesystem>  
#include <thread>
using namespace std;
namespace fs = std::experimental::filesystem;

void SearchFile(const fs::path& pathToShow, string filename,int level=0)
{
    for (const auto& entry : fs::directory_iterator(pathToShow))
    {
       if (fs::is_directory(entry.status()))
        {
          thread thr(SearchFile, entry.path(), filename,  level + 1);
          thr.join();
        }
        else if (entry.path().filename().u8string() == filename)
        {
            cout << "File was found. Path to file:"<< fs::absolute(entry.path()).u8string() << endl;
            terminate();
            return;
        }
    }
}

int main()
{
    string folder_path;
    cout << "Please input name of folder with full path: " << endl;
    getline(cin, folder_path);
    string filename;
    cout << "Please input filename : "<<endl;
    getline(cin, filename);
    SearchFile(fs::path(folder_path), filename);
    _getch();
    return 0;
}

0 个答案:

没有答案