简体   繁体   English

有什么方法可以中止 cin 或 scanf

[英]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.有什么方法可以中止第一个线程 cin/scanf 以从第二个线程打印控制台数据。

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.但我正在寻找一种更好的方法,比如 abort cin 然后重新唤醒它。

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.我找到了一个特殊的解决方案,比如如果它没有得到输入就会中断,一切都以 C 风格完成。 In any case if you are interested check "Head First C" book, section "Interprocess Communication: It's good to talk".无论如何,如果您有兴趣,请查看“Head First C”一书的“进程间通信:交谈很好”部分。

I know it's bit too late.我知道有点晚了。 After a while I was supposed to make cpp multithreaded application again and had the same problem.过了一会儿,我应该再次制作 cpp 多线程应用程序,但遇到了同样的问题。 This time it was done with implementing non blocking input with stdio`s getch() and I think it fits to be the best solution.这次是通过使用 stdio`s getch() 实现非阻塞输入完成的,我认为它适合成为最佳解决方案。

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)我不知道以下解决方案是否足够标准,但它适用于我的 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.不要问我现在如何重用那个 state 中的cin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM