C ++ Ansynchronous IO的意外结果

时间:2017-12-12 09:28:13

标签: c++ io c++17

从Linux命令行我需要运行“foo | bar”。我正在编码吧,它从标准中读取输入(来自foo)。请注意,foo无限期运行。

以下代码模拟了问题。

#include <iostream>
#include <string>
#include <thread>
#include <sstream>
#include <assert.h>
#include <mutex>

std::mutex m{};

class Reader {

private:

    std::istream& in;
    std::thread* myThread = nullptr;
    bool threadContinue = false;

public:

    Reader(std::istream& in) :
            in { in }
    {
        using namespace std;
        threadContinue = true;
        myThread = new thread { [&]() {
            while(this->threadContinue) {
                m.lock();
                cout << "." << in.peek() << " ";
                while(in.peek()>=0) {
                    string line {};
                    getline(in, line);
                    cout << line << " "; // Do something important...
                }
                m.unlock();
                if(!this->threadContinue) {
                    break;
                }
                this_thread::sleep_for(std::chrono::milliseconds(100));
            }
            cout << "STOPPED" << endl;
        } };
    }

    void stop() {
        assert(threadContinue);
        threadContinue = false;
        myThread->join();
        delete myThread;
        myThread = nullptr;
    }

};

int main() {
    using namespace std;
    stringstream io { };
    Reader r { io };

    m.lock();
    io << "A" << endl;
    io << "B" << endl;
    io << "C" << endl;
    io.flush();
    m.unlock();

    this_thread::sleep_for(std::chrono::milliseconds(300));

    m.lock();
    io << "D" << endl;
    io << "E" << endl;
    io << "F" << endl;
    io.flush();
    m.unlock();

    this_thread::sleep_for(std::chrono::milliseconds(300));

    r.stop();
    return 0;
}

输出为.65 A B C .-1 .-1 .-1 .-1 .-1 STOPPED

我做错了什么?我也想要D E F处理。

我可以在没有Boost的C ++ 17中实现这一点吗?

[...我试过使用peek(),getline()而没有偷看,并考虑了流的属性,但无济于事......]

[...我添加了一个互斥锁并对流进行了受控访问,但这没有帮助,输出与以前一样......]

0 个答案:

没有答案