简体   繁体   English

在C ++中,使用一个线程从文件中读取一行,并使用另一个线程来处理(多线程)

[英]Read a line from file using one thread and processing using another thread in C++ (Multi-threading)

New to threading. 线程新手。 I would like to have two separate threads that do two different things: 我想有两个单独的线程来做两种不同的事情:

ThreadA: read a file, line by line from an input file ThreadA:从输入文件中逐行读取文件

ThreadB: do things with the line that is previously read ThreadB:使用先前读取的行执行操作

How can I achieve this? 我该如何实现? Thanks in advance 提前致谢

    class A
    {
    //...
    public:
        void processFile(ifstream& input, string& s)
        {
            //read file line by line in ThreadA
            //process that line in ThreadB
        }
    };

    int main()
    {
        // ?
    }

For the assignment to make sense, one thread should be reading a new line of input while the other thread is processing the previously read line. 为了使分配有意义,一个线程应该读取新的输入行,而另一个线程正在处理先前读取的行。

To answer the question as posed, one may use std::async. 要回答提出的问题,可以使用std :: async。 Include-file is <future>. 包含文件为<future>。 See this near-duplicate . 看到这近乎重复

I am tempted to post a correct program. 我很想发布正确的程序。

EDIT. 编辑。 I cannot help myself. 我无能为力。 This, like so many things, is simple once it's understood (and you know some tricks). 就像很多事情一样,一旦被理解(并且您知道一些技巧),它就很简单。

WARNING SPOILER ALERT You (OP) should not read on until after you have turned in the assignment. 警告扰流板警报上交作业后,才可以继续阅读(OP)。

int main() {
    std::ifstream input("foo.txt"); // Or whatever

    using std::string;
    using std::getline;
    using std::async;
    using std::move;

    // The function that processes the line ...
    // Notice that "line" is bound by value. Using a reference,
    // (const string &line) would create a conflict between threads.
    auto process = [](const string line)->bool {
        return !!(std::cout << line << std::endl); // or whatever...
    };

    string line;
    // The bang-bang !! turns the result of getline into bool
    bool line_ready = !!getline(input, line); // Read first line
    bool process_ok = true;
    while (line_ready && process_ok) {
        auto handle = async(std::launch::async, process, move(line)); // Launch thread
        line_ready = !!getline(input, line); // Fetch next line while processing previous
        process_ok = handle.get(); // Wait for processing to finish
    }
    return (process_ok && input.eof()) ? 0: -1;
}

Threading is a difficult concept to get your mind around. 线程化是一个很难理解的概念。

Conceptually, threads provide parallel execution paths, which appear to execute concurrently. 从概念上讲,线程提供了并行执行路径,这些路径似乎是并行执行的。 On a multiple core processor they may actually be running simultaneously. 在多核处理器上,它们实际上可能同时运行。 On a single core processor, they don't actually run concurrently, but they appear to. 在单个核心处理器上,它们实际上并不并发运行,但看起来可以并发运行。

To use multi-threading effectively, you have to be able to break down a problem in a way where you can imagine that having two functions running simultaneously will benefit you. 为了有效地使用多线程,必须以某种方式解决问题,使您可以想象同时运行两个功能将使您受益。 In your case, you desire to read information in one function, while processing the information in another completely separate function. 在您的情况下,您希望在一个功能中读取信息,而在另一个完全独立的功能中处理信息。 Once you can see how to do that, you just have to run the functions on separate threads, and figure out how to get the information safely from one function to the other. 一旦看到如何做到这一点,您只需要在单独的线程上运行这些函数,并弄清楚如何安全地将信息从一个函数传递到另一个函数。

I would suggest writing a function that reads from the file, and stores the information in a queue or buffer of some sort. 我建议编写一个从文件读取的函数,并将信息存储在某种队列或缓冲区中。 Write another function that takes information from the buffer or queue, and processes the information. 编写另一个函数,该函数从缓冲区或队列中获取信息并处理该信息。 Adhere to the rule that the read function only writes to the queue, and the processing function only reads from the queue. 遵守以下规则:读取功能仅写入队列,处理功能仅从队列读取。

Once you have those functions constructed, tackle the issue of running the functions on threads. 构造完这些功能后,请解决在线程上运行功能的问题。 The general concept is that you will launch a thread with the read function, and another thread with the processing function. 一般概念是,您将使用读取功能启动一个线程,并使用处理功能启动另一个线程。 Then you have to 'join' the threads when they get done doing what they are doing. 然后,当它们完成自己正在做的事情时,您必须“加入”线程。

For the read thread, it is straight forward. 对于读取线程,它是直接的。 Once the file has been read, and the information is all in the queue, it is done. 读取文件并将信息全部放入队列后,就完成了。 The processing thread is a little more difficult. 处理线程有点困难。 It needs to figure out when the information is going to quit coming. 它需要弄清楚何时将要退出信息。 It may be necessary for the reading function to add something to the queue to indicate that the reading is done. 读取功能可能需要向队列添加一些内容以指示读取已完成。

There are a number of ways to create the threads and run the functions on the threads. 有多种方法可以创建线程并在线程上运行函数。 I'm pretty sure that your instructor is recommending ways of doing that. 我很确定您的老师会推荐这样做的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM