用一个对象开启多个线程并返回结果

Opening multiple threads with an object and returning a result

我试图通过一个循环打开多个线程,其中每个线程都是一个 class 的实例,它的构造函数重载了这样它会自动运行所需的代码,这个函数 returns 一个unordered_list,我想为那个特定的实例检索它,然后附加到最终的 unordered_list

我尝试过使用 futures 和 promises,但是当我尝试时,我最终弄糊涂了。这个项目旨在挑战我并帮助我学习 c++ 中的多线程。

    //class to be instantiated per thread   
    class WordCounter {
    public:
        std::unordered_map<std::string, int> thisWordCount;
        std::string word;

        WordCounter(std::string filepath) {}//will be overloaded
        ~WordCounter() {}//destructor

        std::unordered_map<std::string, int>operator()(std::string filepath) const {}//overloaded constructor signature
        std::unordered_map<std::string, int>operator()(std::string currentFile) {//overloaded constructor implementation
            fstream myReadFile;
            myReadFile.open(currentFile);
            if (!!!myReadFile) {
                cout << "Unable to open file";
                exit(1); // terminate with error
            }
            else if (myReadFile.is_open()) {
                while (!myReadFile.eof()) {
                    while (myReadFile >> word) {
                        ++thisWordCount[word];
                    }
                }
            }
            myReadFile.close();

            return thisWordCount;
        }
    };


    int main(int argc, char** argv)
    {
        std::vector<std::thread> threads;//store instantiated threads using WordCounter
        static std::unordered_map<std::string, int> finalWordCount; //append result from each thread to this unordered_list only when a particular thread finish's reading a file
        vector<string> fileName = { "input1.txt" , "input2.txt" };//filepaths to the files used

        for (int i = 0; i < fileName.size(); ++i)//loop through vector of filepaths to open a thread for each file to then be processed by that thread
        {
            std::string currentFile = DIR + fileName[i];
            std::thread _newThread(new WordCount(currentFile); //is this how the thread would be created?
            threads.emplace_back(_newThread);//store new thread in a vector

//I want to read through the vector when a particular thread finishes and append that particular threads result to finalWordCount

        }

}

多线程处理您的代码

让我们从编写多线程 countWords 函数开始。这将使我们对代码需要做什么有一个高级概述,然后我们将填补缺失的部分。

写作countWords

countWords 计算文件名向量中每个文件中的词频。它并行执行此操作。

步骤概述:

  • 创建线程向量
  • 提供一个存储最终结果的地方(这是finalWordCount变量)
  • WordCounter 创建回调函数,以便在完成后调用
  • 使用 WordCounter 对象为每个文件启动一个新线程。
  • 等待广告完成
  • return finalWordCount

A WordCounter 对象在线程启动时将文件名作为输入。

缺失部分:

  • 我们还需要写一个makeWordCounter函数

实现:

using std::unordered_map;
using std::string; 
using std::vector; 

unordered_map<string, int> countWords(vector<string> const& filenames) {
    // Create vector of threads
    vector<std::thread> threads;
    threads.reserve(filenames.size());

    // We have to have a lock because maps aren't thread safe
    std::mutex map_lock;

    // The final result goes here
    unordered_map<std::string, int> totalWordCount; 

    // Define the callback function
    // This operation is basically free
    // Internally, it just copies a reference to the mutex and a reference
    // to the totalWordCount
    auto callback = [&](unordered_map<string, int> const& partial_count) {
        // Lock the mutex so only we have access to the map
        map_lock.lock(); 
        // Update the map
        for(auto count : partial_count) {
            totalWordCount[count.first] += count.second; 
        }
        // Unlock the mutex
        map_lock.unlock(); 
    };

    // Create a new thread for each file
    for(auto& file : filenames) {
        auto word_counter = makeWordCounter(callback); 
        threads.push_back(std::thread(word_counter, file)); 
    }

    // Wait until all threads have finished
    for(auto& thread : threads) {
        thread.join(); 
    }

    return totalWordCount; 
}

写作makeWordCounter

我们的函数 makeWordCounter 非常简单:它只是创建一个 WordCounter 函数,该函数以回调为模板。

template<class Callback>
WordCounter<Callback> makeWordCounter(Callback const& func) {
    return WordCounter<Callback>{func}; 
}

写一个WordCounterclass

成员变量:

  • 回调函数(我们不需要任何其他东西)

函数

  • operator() 使用文件名
  • 调用 countWordsFromFilename
  • countWordsFromFilename 打开文件,确保它没问题,然后用文件流
  • 调用 countWords
  • countWords 读取文件流中的所有单词并计算计数,然后使用最终计数调用回调。

因为WordCounter实在是太简单了,所以直接做成一个struct。它只需要存储Callback函数,通过使callback函数public,我们不必写构造函数(编译器使用聚合初始化自动处理)。

template<class Callback>
struct WordCounter {
    Callback callback;

    void operator()(std::string filename) {
        countWordsFromFilename(filename); 
    }
    void countWordsFromFilename(std::string const& filename) {
        std::ifstream myFile(filename);
        if (myFile) {
            countWords(myFile); 
        }
        else {
            std::cerr << "Unable to open " + filename << '\n'; 
        }
    }
    void countWords(std::ifstream& filestream) {
        std::unordered_map<std::string, int> wordCount; 
        std::string word; 
        while (!filestream.eof() && !filestream.fail()) {
            filestream >> word; 
            wordCount[word] += 1;
        }
        callback(wordCount); 
    }
};

完整代码

您可以在此处查看 countWords 的完整代码:https://pastebin.com/WjFTkNYF

我添加的唯一内容是 #includes。

回调和模板 101(应原始发帖者的要求)

模板是编写代码时可以使用的简单而有用的工具。它们可以用来消除相互依赖;使算法通用(因此它们可以与您喜欢的任何类型一起使用);它们甚至可以让您避免调用虚拟成员函数或函数指针,从而使代码更快、更高效。

模板化 class

让我们看一个非常简单的 class 模板来表示一对:

template<class First, class Second>
struct pair {
    First first;
    Second second; 
};

在这里,我们将 pair 声明为 struct,因为我们希望所有成员都是 public。

请注意,没有 First 类型,也没有 Second 类型。 当我们使用名称 FirstSecond,我们真正要说的是“在 pair class 的上下文中,名称 First 将代表对 class 的 First 参数, 而名称 Second 将代表对中的第二个元素 class.

我们可以很容易地把它写成:

// This is completely valid too
template<class A, class B>
struct pair {
    A first;
    B second; 
};

使用pair非常简单:

int main() {
    // Create pair with an int and a string
    pair<int, std::string> myPair{14, "Hello, world!"}; 

    // Print out the first value, which is 14
    std::cout << "int value:    " << myPair.first << '\n';
    // Print out the second value, which is "Hello, world!"
    std::cout << "string value: " << myPair.second << '\n';
}

就像普通的class一样,pair可以有成员函数、构造函数、析构函数……任何东西。因为pair就是这么简单的class,编译器会自动为我们生成构造函数和析构函数,我们不用担心。

模板化函数

模板函数看起来与常规函数相似。唯一的区别是它们在函数声明的其余部分之前有 template 声明。

让我们编写一个简单的函数来打印一对:

template<class A, class B>
std::ostream& operator<<(std::ostream& stream, pair<A, B> pair) 
{
    stream << '(' << pair.first << ", " << pair.second << ')'; 
    return stream; 
}

我们可以给它任何我们想要的pair,只要它知道如何打印对的两个元素:

int main() {
    // Create pair with an int and a string
    pair<int, std::string> myPair{14, "Hello, world!"}; 

    std::cout << myPair << '\n'; 
}

这输出 (14, Hello, world).

回调

C++ 中没有 Callback 类型。我们不需要一个。回调只是你用来表明发生了什么事的东西。

让我们看一个简单的例子。这个函数寻找逐渐变大的数字,每次找到一个,它就调用 output,这是我们提供的一个参数。在这种情况下,output 是一个回调,我们用它来表示找到了一个新的最大数字。

template<class Func>
void getIncreasingNumbers(std::vector<double> const& nums, Func output) 
{
    // Exit if there are no numbers
    if(nums.size() == 0) 
        return; 

    double biggest = nums[0]; 
    // We always output the first one
    output(biggest); 
    for(double num : nums) 
    {
        if(num > biggest) 
        {
            biggest = num; 
            output(num); 
        }
    }
}

我们可以用很多不同的方式使用 getIncreasingNumbers。例如,我们可以过滤掉不大于前一个的数字:

std::vector<double> filterNonIncreasing(std::vector<double> const& nums) 
{
    std::vector<double> newNums; 
    // Here, we use an & inside the square brackets
    // This is so we can use newNums by reference
    auto my_callback = [&](double val) { 
        newNums.push_back(val); 
    };
    getIncreasingNumbers(nums, my_callback); 
    return newNums; 
}

或者我们可以打印出来:

void printNonIncreasing(std::vector<double> const& nums) 
{
    // Here, we don't put anything in the square brackts
    // Since we don't access any local variables
    auto my_callback = [](double val) {
        std::cout << "New biggest number: " << val << '\n'; 
    };
    getIncreasingNums(nums, my_callback); 
}

或者我们可以找出它们之间最大的差距:

double findBiggestJumpBetweenIncreasing(std::vector<double> const& nums)
{
    double previous; 
    double biggest_gap = 0.0; 
    bool assigned_previous = false;
    auto my_callback = [&](double val) {
        if(not assigned_previous) {
            previous = val; 
            assigned_previous = true;
        }
        else 
        {
            double new_gap = val - previous; 
            if(biggest_gap < new_gap) {
                biggest_gap = new_gap; 
            }
        }
    };
    getIncreasingNums(nums, my_callback); 
    return biggest_gap;
}