Home > other >  End thread from parent main vs. another thread
End thread from parent main vs. another thread

Time:08-07

I'm new to C and am trying to have two threads run:

i) Thread that keeps looping until an atomic bool is flipped.

ii) A thread that polls for input from keyboard and flips the atomic bool.

I seem to be unable to get std::cin.get() to react to an input unless it is assigned its' own thread (like below). Why? Would it not then be set from the parent main thread?

#include <iostream>
#include <iomanip> // To set decimal places.
#include <thread> //std::thread
#include <atomic> //for atomic boolean shared between threads.
#include <math.h>

#define USE_MATH_DEFINES //For PI

std::atomic<bool> keepRunning(false); //set to false to avoid compiler optimising away.

void loop(){
    int t = 1;
    while(!keepRunning.load(std::memory_order_acquire)) //lower cost than directly polling atomic bool?
    {
        //Write sine wave output to console.
        std::cout << std::setprecision(3) << sin(M_PI * 2 * t/100) << std::endl;
        (t<101)? t   : t = 1;
    }
}

//This works, as opposed to stopping in main.
void countSafe(){
    int j = 1;
    while (j<1E7)
    {
        j  ;
    }
    keepRunning.store(true, std::memory_order_release); //ends the loop thread.     
}



int main(){
    
    std::thread first (loop); //start the loop thread
    std::thread second (countSafe); //start the countSafe thread. Without this it doesn't work.

    //Why does polling for std::cin.get() here not work?

    //std::cin.get(); //wait for key press. puts in buffer..?
    //keepRunning.store(true, std::memory_order_release); //Set stop to true.

    second.join(); //pause to join.
    first.join(); //pause to join
    
    

    return 0;
}

CodePudding user response:

I'm not quite sure what your problem is, but use of cin.get() might be part of it. Let's simplify with this code:

#include <iostream>

using namespace std;


int main(int, char **) {
    cout << "Type something: ";
    cin.get();
    cout << "Done.\n";
}

Try that code and run it. Then type a single character. Chances are that the code won't recognize it. And you can type all you want until you hit return.

This is complicated, but your program doesn't actually receive the characters until you hit return unless you play other games. Like I said, it's complicated.

It's possible behavior is different on Windows, but this is the behavior on Mac and Linux.

So is it "not working" because you tried typing a space but you really need to use Return?

  • Related