I have a multithreaded program in which on thread waits for input through a terminal and the other will get data from the socket. Is there any way to abort first threads cin/scanf to print in console data from second thread.
I think to kill the first thread, print data from second thread then run first thread again. But I'm looking for a better method, something like abort cin then reawoke it.
void thread1(){
    cin>>string;
    doSomething();
}
void thread2(){
    cout<<getSomeData();
} 
In usual case, it won't print data till something would be entered from keyboard.
[EDIT]
I found a particular solution, like if it doesn't get input it will interrupt, everything was done in C style. In any case if you are interested check "Head First C" book, section "Interprocess Communication: It's good to talk".
I don't know if the following solution is standard enough, but it works on both my Fedora Linux (GCC 10.3) & Windows 10 (MSVC 16.11)
#include <iostream>
#include <csignal>
int main()
{
    std::signal(SIGINT, [] (int s)
    {
        std::signal(s, SIG_DFL);
        std::fclose(stdin);
        std::cin.setstate(std::ios::badbit); // To differenciate from EOF input
    });
    std::string input;
    std::cout << "Input CTRL+C or EOF now!" << std::endl;
    std::getline(std::cin, input);
    std::cout << (std::cin.bad() ? "\rinterrupted" : "eof") << std::endl;
}
Don't ask me how to reuse cin from that state now.
I know it's bit too late. After a while I was supposed to make cpp multithreaded application again and had the same problem. This time it was done with implementing non blocking input with stdio`s getch() and I think it fits to be the best solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With