简体   繁体   English

如何从其他线程中断 std::cin(std::cin.getline) executuion

[英]How to break std::cin(std::cin.getline) executuion from other thread

I have some code:我有一些代码:

while(true) {
    std::string message;
    
    std::cin >> message; // break it
    
    // send message
  }

I want to interrupt waiting for user input from std::cin from other thread.我想中断等待来自其他线程的std::cin用户输入。
How can I do it?我该怎么做? Thanks in advance!提前致谢!

std::cin is a blocking call that can not be interrupted. std::cin 是一个不能被中断的阻塞调用。

This thread here seems to have some non-blocking alternatives: https://stackoverflow.com/a/40812107/2562287这里的线程似乎有一些非阻塞替代方案: https : //stackoverflow.com/a/40812107/2562287

If you used a non blocking alternative for std::cin along with an boolean (threadsafe from either a mutex or being atomic, preferably the latter), you could set the boolean on the other thread and read the boolean on the input thread, if the boolean is either true or false then exit the input function.如果您使用 std::cin 的非阻塞替代方案以及布尔值(来自互斥锁或原子的线程安全,最好是后者),您可以在另一个线程上设置布尔值并在输入线程上读取布尔值,如果布尔值为真或假,然后退出输入函数。

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

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