c++ - 线程输入问题

标签 c++ multithreading io

我是线程的新手,正在尝试创建一个基本的异步输入程序。

[ main.cpp ] :

#include <iostream>
#include <thread>
#include <string>
#include <chrono>

void ThreadedOutput(void) {
    while(true) {
        std::string output="Distracting output!\n";
        std::this_thread::sleep_for(std::chrono::seconds(3));
        std::cout << output;
    }
}

int main(void) {
    std::thread active_thread(&ThreadedOutput);
    active_thread.detach();

    std::string input;

    while(input!=std::string("password")) {
        std::cin >> input;
    }

    return 0;
}

这样做的目的是在用户输入文本时打印输出。 但是,它将输出打印到输入线上,这会干扰输入。 有没有办法让它打印在输入行上方?

截图: incorrect

最佳答案

您可以将 cin 缓冲区重定向到一个文件(或其他流),然后用 cout 显示它。

How to redirect cin and cout to files?

现在的问题是:如何不受干扰地显示cout?使用互斥体和 lock_guard

希望对你有帮助,

关于c++ - 线程输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17642232/

相关文章:

Java I/O : How to Print Loop Outputs to one file?

java - AtomicInteger 是为多线程应用程序提供计数器的好解决方案吗?

linux - SSD的“典型”延迟意味着什么?

c++ - 对于 Windows 上的 C++,我应该使用哪个 IDE?

c++ - 防止意外隐藏(由 CRTP mixin 提供的方法)

c# - 僵局澄清?

C++ 线程安全 - map 读取

Java:为什么在调用 .readObject() 时,具有引用泛型类型的 ArrayList 不计为强制转换?

c++ - 为什么 C++ 不允许我使用 typeof?

C++:如何初始化非整数类型的静态成员变量?