'Is there any method to abort cin or scanf

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".



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chnossos
Solution 2 magnagag