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

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

我有一些代码:

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

我想中断等待来自其他线程 std::cin 的用户输入。
我该怎么做?提前致谢!

std::cin是阻塞调用,不能中断

这里的这个线程似乎有一些 non-blocking 替代方案:

如果您对 std::cin 使用了一个非阻塞替代方案以及一个布尔值(来自互斥锁或原子的线程安全,最好是后者),您可以在另一个线程上设置布尔值并读取布尔值在输入线程上,如果布尔值是 true 或 false,则退出输入函数。