CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13

Thread: cin isn't blocking

  1. #1
    Join Date
    Dec 2019
    Posts
    8

    cin isn't blocking

    I'm trying to do a command loop but cin isn't blocking and it just loops until crashes.


    Code:
    public:
        void loop()
        {
            std::string selection;
            cout << "Initializing Manual Sampler Thread" << endl;
            while(true)
            {
            
                cout << "Command>" << endl;
                
                std::string selection;
                //std::getline(std::cin, selection);
                cin >> selection;
                
                
                cout << selection;
            }
                
            
        }

  2. #2
    Join Date
    Nov 2018
    Posts
    38

    Re: cin isn't blocking

    Maybe your input stream is in an error state.
    Code:
    if ( cin >> selection ) {
        cout << selection;
    } else {
        std::cerr << "cin is borked - do something!" << std::endl;
        break;  // no more while(true)
    }

  3. #3
    Join Date
    Dec 2019
    Posts
    8

    Re: cin isn't blocking

    Its borked. Now what do I do?


    Shadow Engine (RavenTek) Version 1.0 Build 1.0
    Developed by Twilight Raven Games
    -------------------------------------
    Starting CORE
    Performing initialization of threads
    Host a game? (Y/N)
    n
    Host game?
    Core intializing
    Initializing CORE 1.0
    Initializing Clock thread
    Initializing Task Manager Thread
    Initializing Event Manager Thread
    Intializing Scheduler Thread
    Initializing MessageManager thread
    Initializing Manual Sampler Thread
    Command:
    cin is borked - do something!
    Program ended with exit code: 0
    Last edited by tedgress; December 28th, 2019 at 10:29 AM.

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,267

    Re: cin isn't blocking

    When a stream is in fail state, then just clear the error.

    Code:
    if (!(cin >> selection)) {
        cin.clear();
        cin >> selection;
    }
    
    cout << selection;
    The issue, though, is what has caused the cin stream to enter fail state?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.4)

  5. #5
    Join Date
    Dec 2019
    Posts
    8

    Re: cin isn't blocking

    That's what I don't understand. I am inputting just a simple character, then I go into the loop where it is supposed to be blocking.

  6. #6
    Join Date
    Nov 2018
    Posts
    38

    Re: cin isn't blocking

    Shadow Engine (RavenTek) Version 1.0 Build 1.0
    Developed by Twilight Raven Games
    -------------------------------------
    Starting CORE
    Performing initialization of threads
    Host a game? (Y/N)
    n
    Host game?
    Core intializing
    ...
    So is this your magnum opus, or have you just found some source code?
    Because if it is downloaded code, it would be wise of you to tell us.
    Pin-hole guesses on your part tell us nothing about wider issues you might be facing.

    > That's what I don't understand. I am inputting just a simple character
    Well that's all it takes to get the stream into an error state.
    You type in the wrong character at the wrong moment, and badly written s/w will make a complete dog's breakfast of it.

    Code:
    cout << "Host a game? (Y/N)";
    int dummy;
    cin >> dummy;
    You type in "n" and boom, instant error state.

    Show us how the initial Q&A is handled.

    > Host game?
    See, now this is interesting.
    It looks like another prompt from the program, presumably with another cin?
    But since you didn't actually type anything in for this second prompt, was the stream already in an error state at that point?

    I see lots of mention of "threads".
    How do you know which thread has control of the cin stream?
    Because multiple threads fighting over cin will not end well for you.

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,267

    Re: cin isn't blocking

    Quote Originally Posted by tedgress View Post
    That's what I don't understand. I am inputting just a simple character, then I go into the loop where it is supposed to be blocking.
    Well, the simplest way is to always put the cin stream into a good state with cin.clear() before any input is attempted. Then irrespective of what has caused the cin stream fail state, your input will be OK if the correct type of required input is entered.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.4)

  8. #8
    Join Date
    Feb 2017
    Posts
    567

    Re: cin isn't blocking

    Quote Originally Posted by salem_c View Post
    I see lots of mention of "threads".
    How do you know which thread has control of the cin stream?
    Because multiple threads fighting over cin will not end well for you.
    Yes I bet this is the problem. The OP is not reading the standard input from inside the main thread.

  9. #9
    Join Date
    Dec 2019
    Posts
    8

    Re: cin isn't blocking

    Hi
    First of all, this is my Magnum Opus. This bit of code is just a tiny piece of my game engine I've been working on for the past three years on and off.
    Second, my cin is in a continuous error state. I have been clearing cin before doing an input stream. I don't know why it would be a race condition since there are several threads but only one thread handle any kind of input.


    The present state of my code (For testing purposes) is as follows:
    class ManualSampler
    {
    public:
    void loop()
    {
    std::string selection;

    cout << "Initializing Manual Sampler Thread" << endl;
    while(true)
    {
    cout << "Command:" << endl;
    //std::string input;
    //cout << "Enter command>" << endl;
    //cin >> input;
    //C//ommandsFSM(input);
    cin.clear();
    if (!(cin >> selection)) {
    cout << "CIN is in an error state" << endl;
    cin.clear();

    }
    cin >> selection;
    cout << selection << endl;
    cin.clear();
    cin >> selection;
    cout << selection << endl;
    cin.clear();
    cin >> selection;
    cout << selection;

    cout << selection;
    }



    }

    void CommandsFSM(std::string input);
    };
    And the output is:
    Shadow Engine (RavenTek) Version 1.0 Build 1.0
    Developed by Twilight Raven Games
    -------------------------------------
    Starting CORE
    Performing initialization of threads
    Host a game? (Y/N)
    Y
    Host game?
    Core intializing
    Initializing CORE 1.0
    Initializing Clock thread
    Initializing Task Manager Thread
    Initializing Event Manager Thread
    Intializing Scheduler Thread
    Initializing MessageManager thread
    Initializing Manual Sampler Thread
    Command:
    Program ended with exit code: 0
    You know what, I didn't think of this. The initialization code for each of the threads uses cout and outputs a debugging statement. All of the threads except the last (Manual Sampler) have a cout and then Manual Sampler hops on a thread and gets is supposed to get text commands from the user. Could this be the problem? But none of the other threads except Manual Sampler just do cout not cin. How do I go about fixing this?

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,267

    Re: cin isn't blocking

    Streams (input & output) and containers are not thread-aware. If you use the same stream/container in multiple threads, then you need to synchronise (including cout).

    Assuming cin is OK for Host a game input (as Y seems to be input OK), then between that and obtaining command something is 'upsetting' the cin stream. I suggest that you trace through the state of cin to see where it is being set to the failed state. cin.good() should be true.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.4)

  11. #11
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,797

    Re: cin isn't blocking

    Please, edit your post replacing quote tags with the code ones and adding the proper code indentations.
    Otherwise your "snippets" are absolutely unreadable!
    Victor Nijegorodov

  12. #12
    Join Date
    Nov 2018
    Posts
    38

    Re: cin isn't blocking

    TBH, I would create a side project just to investigate cout, cin and a small number of threads.
    But even then, "it works" would prove nothing useful, though failure would clearly demonstrate that you have a problem.
    You would need to read your implementations documentation to find out for sure.

    > Could this be the problem?
    Yes.
    For one thing, cout is tied to cin, so just one cout in a thread could easily poison the well for using cin at all.

    > How do I go about fixing this?
    By taking a big step back and having a good think about your approach to threads.
    You don't create a multi threaded program without a solid PLAN.

    Otherwise, you face a death march of chasing endless race conditions with badly hacked 'solutions' that risk making things worse rather than better in the long run.

    Every global resource (like cout, cin, your GUI library, the file system, ...) should be assumed to be off-limits to anything other than the main thread unless you have specific documentation indicating that it is thread safe.

    Large swathes of the STL are not thread safe as well, so you either need
    - a mutex to guard access to the object
    - establish clear ownership rules to track who has access and when.

    Your main should be the overall controller of proceedings, managing all the interaction with the outside world.
    Your threads should by comparison be dumb workers. They interact with main via the likes of mutexes and message queues.

    So if your worker thread wants to log a message, it should send it to main first.

  13. #13
    Join Date
    Feb 2017
    Posts
    567

    Re: cin isn't blocking

    Quote Originally Posted by tedgress View Post
    How do I go about fixing this?
    Do all user input/output from the main thread.

    Then set up a message system, that is some way to pass information between threads.

    If you do this you're on solid traditional ground and don't have to fiddle with shaky fixes that "work" until they suddenly don't. It's not for nothing the main thread is often referred to as the GUI-thread.
    Last edited by wolle; December 31st, 2019 at 04:35 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)