【发布时间】:2019-08-20 04:56:11
【问题描述】:
将值无限打印到控制台的线程和从控制台获取用户输入的主线程,但输入值与该线程的输出混合。
确实给了我关于如何进一步前进的提示,但我无法提出自己的解决方案(因为我是 c++ 新手)。
using namespace std;
mutex mtx;
void foo()
{
while (1)
{
usleep(1000000);
cout << "Cake\n";
}
}
int main()
{
mtx.lock();
thread t1(foo);
string x;
while (true)
{
cin >> x;
edit//fflush(stdin);
cout << x << "\n";
}
t1.join();
mtx.unlock();
return 0;
}
编辑 1:
好吧,更准确地说,我真正想要的是,
IN 终端(目前)
output:cake (which prints every second)
output:cake
output:cake
output:cake
input:hi
output:hicake (still yet to give the enter it echo's the input to console)
output:cake
我在终端中真正想要的是输入独立于输出
output:cake
output:cake
output:cake
input:hi
output:cake
output:cake
input:hi(waiting still for enter)
//and when enter is pressed it should print to the console
output:hi
output:cake
注意:禁用回声没有帮助。
编辑 2: 我发布的答案是数据处理,其中并发操作在给定命令上停止。
【问题讨论】:
-
你在一段时间之前锁定了你的互斥锁,然后在一段时间内解锁......你应该解锁/锁定相同的次数
-
对不起,我现在已经编辑了代码,但即使在那之后我也无法获得所需的解决方案
-
fflush(stdin);是未定义的行为,没有任何意义。永远不要那样做。仅在一个线程中使用的互斥锁没有意义。您需要围绕每个线程中对资源的每次访问锁定互斥锁。 -
感谢您的更正,我会牢记这一点@n.m
标签: c++ linux multithreading