Taking input over standard I/O in multithreaded application

ε祈祈猫儿з 提交于 2019-12-11 11:57:30

问题


I have a question about input/output, or basically interaction with the user, in multithreaded applications.

Let's say I have a program that starts three threads and waits for them to end, then starts them again

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

Every thread also outputs data over cout.

I'm looking for a way to take input by the user (cin) without stopping / hindering the main loop in it's progress. How can I realize a solution?

I've tried to create a fourth thread which is running in the background all the time and is waiting for input in cin. For the test case I modified it like this:

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

But the input does not reach this function. I think the problem is that while input_func is waiting for input, other threads are making outputs over cout, but I'm not sure, that's why I'm asking here.

Thanks in advance!


回答1:


I tried something similar to you (using std::thread instead of (presumably) Posix threads). Here is the code and a sample run. Works for me ;)

#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.


来源:https://stackoverflow.com/questions/32350909/taking-input-over-standard-i-o-in-multithreaded-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!