在多线程应用程序中通过标准I / O进行输入 [英] Taking input over standard I/O in multithreaded application
问题描述
我对多线程应用程序中的输入/输出或基本上与用户的交互有疑问。
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);
}
}
每个线程还输出 cout
。
我正在寻找一种方法来接收用户输入的内容( cin
)而又不停止/阻碍主输入循环进行中。我如何实现解决方案?
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?
我试图创建第四个线程,该线程一直在后台运行,并等待 cin $ c中的输入$ c>。对于测试用例,我将其修改为:
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;
}
}
但是输入没有达到此功能。我认为问题在于,当 input_func
等待输入时,其他线程正在通过 cout
进行输出,但是我我不确定,这就是为什么我要在这里问。
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.
预先感谢!
推荐答案
我尝试了类似的操作(使用std :: thread代替(可能是)Posix线程)。这是代码和示例运行。为我工作;)
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.
这篇关于在多线程应用程序中通过标准I / O进行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!