在多线程应用程序中,通过标准I/O接收输入
Taking input over standard I/O in multithreaded application
我有一个关于在多线程应用程序中输入/输出,或者基本上与用户交互的问题。
假设我有一个程序,它启动了三个线程并等待它们结束,然后再次启动它们
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.
相关文章:
- C ++异步键盘输入(标准方式)
- 从标准输入读取文件后读取用户输入
- 如何从标准输入中检测格式化输入错误?
- C++ - 标准输入环路
- 快速读取标准输入缓冲区,无需检查
- 将标准输入中的双精度存储在矢量中
- 如何将 getline 与标准输入一起使用?
- 从 C++ 中的标准输入迭代读取字节
- C++计算标准输入的字数
- 如何从 c++ 中的给定标准输入中获取每个字符的偏移量?
- 为什么此代码从标准输入中少一个输入?
- 如何在C++中从标准输入中获取变量输入
- C++ 从标准输入读取文件名
- 从标准输入读取多个类型时出现问题
- 如何在execl中使用标准输入'<'?
- 如何在 eclipse 中将标准输入从控制台更改为另一个程序
- 流对象来表示文件输入,然后是标准输入?
- 标准输入输出操作如何C++完成
- 从标准输入读取时zmq_poll不侦听信号
- 如何在大量无损压缩图像中挑选重复的图像对(完全相同)?如何在内存中输入标准::哈希