使用对象打开多个线程并返回结果

问题描述 投票:1回答:1

我试图通过一个循环打开多个线程,其中每个线程是一个类的实例,它的构造函数重载,它自动运行所需的代码,此函数返回一个unordered_list,我想为该特定实例检索它然后被附加到最终的unordered_list

我尝试过使用期货和承诺,但是当我尝试时,我最终会感到困惑。这个项目是为了挑战我并帮助我学习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

        }

}

multithreading oop c++11 std unordered-map
1个回答
1
投票

多线程化您的代码

让我们从编写多线程countWords函数开始。这将为我们提供代码需要执行的高级概述,然后我们将填写缺少的部分。

Writing countWords

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

步骤概述:

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

当线程启动时,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; 
}

Writing makeWordCounter

我们的函数makeWordCounter非常简单:它只是创建了一个在回调时模板化的WordCounter函数。

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

Writing a WordCounter class

成员变量:

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

功能

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

因为WordCounter非常简单,我只是把它变成了一个结构。它只需要存储Callback函数,并且通过使callback函数公开,我们不必编写构造函数(编译器使用聚合初始化自动处理它)。

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); 
    }
};

Complete code

你可以在这里看到countWords的完整代码:https://pastebin.com/WjFTkNYF

我添加的唯一的东西是#includes。

回调和模板101(根据原始海报的要求)

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

Templating a class

让我们看一个代表一对的非常简单的类模板:

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

在这里,我们宣布pairstruct,因为我们希望所有成员都公开。

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

我们可以轻松地将其写成:

// 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';
}

就像普通类一样,pair可以有成员函数,构造函数,析构函数......任何东西。因为pair是一个如此简单的类,编译器会自动为我们生成构造函数和析构函数,我们不必担心它们。

Templated functions

模板化函数看起来类似于常规函数。唯一的区别是它们在函数声明的其余部分之前有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)

Callbacks

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.