【问题标题】:Taking input over standard I/O in multithreaded application在多线程应用程序中通过标准 I/O 接收输入
【发布时间】:2015-09-02 10:37:21
【问题描述】:

我对多线程应用程序中的输入/输出或基本上与用户的交互有疑问。

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

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 进行输出,但我不确定,这就是我在这里问的原因。

提前致谢!

【问题讨论】:

  • “但是输入没有到达这个函数。” - 你确定你创建了一个线程来运行input_func吗?在while 循环之前添加cout &lt;&lt; "running input_func()...\n"; 来证明这一点。输出到cout 不应阻止输入,但如果您在屏幕上输入了一半的行并且输出从光标处开始,它可能会弄乱您的终端格式。如果没有终端特定的编码(例如 ncurses),就没有好的解决方案。

标签: c++ multithreading io cout cin


【解决方案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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多