在多线程应用程序中通过标准I / O进行输入

时间:2015-09-02 10:37:21

标签: c++ multithreading io cout cin

在多线程应用程序中,我有一个关于输入/输出或基本上与用户交互的问题。

假设我有一个程序启动三个线程并等待它们结束,然后重新启动它们

int main()
{
   while(true)
   {
      start_thread(1);
      start_thread(2);
      start_thread(3);
      //....
      join_thread(1);
      join_thread(2);
      join_thread(3);
   }
}

每个线程也通过cout输出数据。

我正在寻找一种方法来接受用户(cin)的输入,而不会停止/阻碍主循环的进度。我怎样才能实现解决方案?

我尝试创建第四个在后台运行的线程,并等待cin中的输入。对于测试用例,我修改了它:

void* input_func(void* v)
{
    while(true)
    {
        string input;
        cin >> input;
        cout << "Input: " << input << endl;
    }
}

但是输入没有达到此功能。我认为问题是当input_func等待输入时,其他线程正在输出cout,但我不确定,这就是我在这里问的原因。

提前致谢!

1 个答案:

答案 0 :(得分:1)

我尝试了类似的东西(使用std :: thread而不是(推测)Posix线程)。这是代码和示例运行。适合我;)

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

using std::cout;
using std::cin;
using std::thread;
using std::string;
using std::endl;

int stopflag = 0;

void input_func()
{
    while(true && !stopflag)
    {
        string input;
        cin >> input;
        cout << "Input: " << input << endl;
    }
}

void output_func()
{
    while(true && !stopflag)
    {
        std::this_thread::sleep_for (std::chrono::seconds(1));
        cout << "Output thread\n";
    }
}

int main()
{
    thread inp(input_func);
    thread outp(output_func);

    std::this_thread::sleep_for (std::chrono::seconds(5));
    stopflag = 1;
    outp.join();
    cout << "Joined output thread\n";
    inp.join();

    cout << "End of main, all threads joined.\n";

    return 0;
}


 alapaa@hilbert:~/src$ g++ --std=c++11 threadtzt1.cpp -lpthread -o     threadtzt1
alapaa@hilbert:~/src$ ./threadtzt1 
kOutput thread
djsölafj
Input: kdjsölafj
Output thread
södkfjaOutput thread
öl
Input: södkfjaöl
Output thread
Output thread
Joined output thread
sldkfjöak
Input: sldkfjöak
End of main, all threads joined.