2013-07-14 107 views
2

我对线程非常陌生,并且正在尝试创建一个基本的异步输入程序。螺纹输入问题

[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

+1

你用std :: mutex保护共享资源。控制台也不例外。 –

+0

互斥锁在其他线程正在使用它们时阻塞资源,对吗?然而,我正在尝试与cin同时使用cout。 – object

+0

不,互斥块*代码*尝试使用不是线程安全的共享资源。巨大差距。所以如果你正确地使用它,那么你可以防止你的cout语句在cin尚未返回时执行。在任何有关线程顺序的入门书中都有很好的介绍。不要跳过阅读,线程难以正确,直觉不起作用。 –

回答

0

可以重定向CIN缓冲到一个文件(或其他数据流),然后用COUT显示它。现在

How to redirect cin and cout to files?

的问题就变成了:如何显示COUT无干扰?使用一个互斥锁和一个lock_guard

希望有帮助,