非阻塞的std::getline,如果没有输入就退出

15

目前我有一个从标准输入读取数据的程序,有时候程序需要在没有输入时继续运行,通常这是一个测试脚本,没有所谓的“回车”。

program -v1 -v2 -v3 <input >output

v1 - v3 分别是命令行参数。

基本上,如果不给出“input”,该程序将输出命令行参数及其相应的含义,然后退出。

但是,如果给它一个空的测试文件或者只是在运行后不按回车键运行,它会阻塞在我用来输入命令的 std::getline 上。

while(std::getline(std::cin,foo)
{do stuff}

其中foo是一个字符串。

当没有输入时,如何让代码运行一次并退出?如果有输入,则执行操作会对标准输入中的每一行都执行一次。

切换到使用do-while循环,是否可以在循环之前检查是否有任何输入?

类似这样:

if cin empty
set flag

do
 {do stuff
 check flag}
while(getline)

或者说在 C++ 中非阻塞 I/O 是不可能的吗?

这个问题似乎已经被反复提出,但我找不到一个明确的答案,甚至找不到一个平台无关的答案(这个程序是学术性质的,在 Windows 上编写并在 Unix 上测试)。


那么你的意思是无论如何都要让循环运行一次,然后在getline调用之前如果没有输入就退出? - Syntactic Fructose
可能是在调用std :: getline之前检查数据可用性的重复问题。不幸的是,在标准C ++中可能没有一种便携式的方法来实现这一点。 - jrok
你能使用一些来自C语言的低级函数吗? - Zaffy
3个回答

12
使用std :: cin异步可能是使其工作的唯一方法,因为iostream不设计具有非阻塞行为。以下是示例: Async Example 1 Async Example 2 (printing a space out every 1/10th of a second while accepting CLI input at the same time) 代码已经注释,很容易理解。这是一个线程安全的类,可以让您使用std :: cin异步获取一行。
非常适用于异步CLI getline目的,我电脑上的CPU使用率为0%。它在Windows 10中以Visual Studio 2015 c ++ Win32 Console Debug和Release模式完美运行。如果在您的操作系统或环境中无法正常工作,则太糟糕了。
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <atomic>

using namespace std;

//This code works perfectly well on Windows 10 in Visual Studio 2015 c++ Win32 Console Debug and Release mode.
//If it doesn't work in your OS or environment, that's too bad; guess you'll have to fix it. :(
//You are free to use this code however you please, with one exception: no plagiarism!
//(You can include this in a much bigger project without giving any credit.)
class AsyncGetline
{
    public:
        //AsyncGetline is a class that allows for asynchronous CLI getline-style input
        //(with 0% CPU usage!), which normal iostream usage does not easily allow.
        AsyncGetline()
        {
            input = "";
            sendOverNextLine = true;
            continueGettingInput = true;

            //Start a new detached thread to call getline over and over again and retrieve new input to be processed.
            thread([&]()
            {
                //Non-synchronized string of input for the getline calls.
                string synchronousInput;
                char nextCharacter;

                //Get the asynchronous input lines.
                do
                {
                    //Start with an empty line.
                    synchronousInput = "";

                    //Process input characters one at a time asynchronously, until a new line character is reached.
                    while (continueGettingInput)
                    {
                        //See if there are any input characters available (asynchronously).
                        while (cin.peek() == EOF)
                        {
                            //Ensure that the other thread is always yielded to when necessary. Don't sleep here;
                            //only yield, in order to ensure that processing will be as responsive as possible.
                            this_thread::yield();
                        }

                        //Get the next character that is known to be available.
                        nextCharacter = cin.get();

                        //Check for new line character.
                        if (nextCharacter == '\n')
                        {
                            break;
                        }

                        //Since this character is not a new line character, add it to the synchronousInput string.
                        synchronousInput += nextCharacter;
                    }

                    //Be ready to stop retrieving input at any moment.
                    if (!continueGettingInput)
                    {
                        break;
                    }

                    //Wait until the processing thread is ready to process the next line.
                    while (continueGettingInput && !sendOverNextLine)
                    {
                        //Ensure that the other thread is always yielded to when necessary. Don't sleep here;
                        //only yield, in order to ensure that the processing will be as responsive as possible.
                        this_thread::yield();
                    }

                    //Be ready to stop retrieving input at any moment.
                    if (!continueGettingInput)
                    {
                        break;
                    }

                    //Safely send the next line of input over for usage in the processing thread.
                    inputLock.lock();
                    input = synchronousInput;
                    inputLock.unlock();

                    //Signal that although this thread will read in the next line,
                    //it will not send it over until the processing thread is ready.
                    sendOverNextLine = false;
                }
                while (continueGettingInput && input != "exit");
            }).detach();
        }

        //Stop getting asynchronous CLI input.
        ~AsyncGetline()
        {
            //Stop the getline thread.
            continueGettingInput = false;
        }

        //Get the next line of input if there is any; if not, sleep for a millisecond and return an empty string.
        string GetLine()
        {
            //See if the next line of input, if any, is ready to be processed.
            if (sendOverNextLine)
            {
                //Don't consume the CPU while waiting for input; this_thread::yield()
                //would still consume a lot of CPU, so sleep must be used.
                this_thread::sleep_for(chrono::milliseconds(1));

                return "";
            }
            else
            {
                //Retrieve the next line of input from the getline thread and store it for return.
                inputLock.lock();
                string returnInput = input;
                inputLock.unlock();

                //Also, signal to the getline thread that it can continue
                //sending over the next line of input, if available.
                sendOverNextLine = true;

                return returnInput;
            }
        }

    private:
        //Cross-thread-safe boolean to tell the getline thread to stop when AsyncGetline is deconstructed.
        atomic<bool> continueGettingInput;

        //Cross-thread-safe boolean to denote when the processing thread is ready for the next input line.
        //This exists to prevent any previous line(s) from being overwritten by new input lines without
        //using a queue by only processing further getline input when the processing thread is ready.
        atomic<bool> sendOverNextLine;

        //Mutex lock to ensure only one thread (processing vs. getline) is accessing the input string at a time.
        mutex inputLock;

        //string utilized safely by each thread due to the inputLock mutex.
        string input;
};

void main()
{
    AsyncGetline ag;
    string input;

    while (true)
    {
        //Asynchronously get the next line of input, if any. This function automagically
        //sleeps a millisecond if there is no getline input.
        input = ag.GetLine();

        //Check to see if there was any input.
        if (!input.empty())
        {
            //Print out the user's input to demonstrate it being processed.
            cout << "{" << input << "}\n";

            //Check for the exit condition.
            if (input == "exit")
            {
                break;
            }
        }

        //Print out a space character every so often to demonstrate asynchronicity.
        //cout << " ";
        //this_thread::sleep_for(chrono::milliseconds(100));
    }

    cout << "\n\n";
    system("pause");
}

6
嘿,我投入了很多心血在这个项目上,它运行良好并且得到了非常好的评价。为什么要给我负面评价? - Andrew
2
我不确定为什么这个被踩了,但是我来点个赞! - SDG
2
小提示:continueGettingInputinputLock等变量在析构函数结束时将被释放(也就是未定义的行为,最好情况下会导致崩溃)。你需要将它们改成shared_ptr并通过值在轮询线程中捕获(或许可以将它们打包到一个SharedState结构体中)。 - helmesjo
1
这太棒了,谢谢Andrew。helmesjo,如果将线程命名为t并在类析构函数中添加t.join(),那么是否可以解决这个问题而不使用智能指针?std::atomic没有分配任何内存,所以我认为就不会有垃圾存在了。 - polortiz40
我在Linux上测试了它,它可以工作,但可能不是预期的方式。特别是cin.peek()会阻塞,因此只有在cin已关闭时才调用this_thread.yield() - Petr Vilím

0
你可以使用 cin.peek 来检查是否有可读内容,如果有,则调用 getline。但是,单独使用非阻塞的 getline 是不可能的。

8
如果没有可用的输入,那也会被阻塞。 - jrok
1
根据标准,cin.peek 应该会阻塞,因为:如果 good() 为 false,则返回 traits::eof()。否则,返回 rdbuf()->sgetc()。 所以就我所知,不可能使用 peek() 以非阻塞的方式检查流。 - Sergey.quixoticaxis.Ivanov

0

你可以使用istream::readsome()方法很容易地创建一个非阻塞的std::getline等效函数。该方法读取可用的输入,最多到达缓冲区大小,而不会阻塞。

这个函数总是立即返回,但如果流上有一行可用,它将捕获该行。部分行存储在静态变量中,直到下一次调用。

bool getline_async(std::istream& is, std::string& str, char delim = '\n') {

    static std::string lineSoFar;
    char inChar;
    int charsRead = 0;
    bool lineRead = false;
    str = "";

    do {
        charsRead = is.readsome(&inChar, 1);
        if (charsRead == 1) {
            // if the delimiter is read then return the string so far
            if (inChar == delim) {
                str = lineSoFar;
                lineSoFar = "";
                lineRead = true;
            } else {  // otherwise add it to the string so far
                lineSoFar.append(1, inChar);
            }
        }
    } while (charsRead != 0 && !lineRead);

    return lineRead;
}

1
这实际上似乎没有读取任何内容(至少在从控制台输入读取时不是这样)。使用上述代码,我无法在控制台中输入。 - helmesjo
我正在Windows下工作,但它对我也没有读取任何内容。 - Jeroen Lammertink
你能详细说明一下你是如何使用这个函数的吗?我已经在Windows和Linux上成功测试过了。 - PeteBlackerThe3rd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接