在多线程应用程序中,通过标准I/O接收输入

Taking input over standard I/O in multithreaded application

本文关键字:输入 标准 应用程序 多线程      更新时间:2023-10-16

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

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

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输出,但我不确定,这就是为什么我在这里问。

提前感谢!

我尝试过类似的事情(使用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 threadn";
    }
}
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 threadn";
    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.