【发布时间】:2018-05-11 20:01:26
【问题描述】:
我们必须编写将创建两个线程的程序。第一个线程会从键盘请求字母,然后它会向等待它的第二个线程发送一个信号。然后它将这个字母更改为大写字母,如果这个字母不是“E”,它将向线程一发送另一个信号。什么会使线程再次运行,直到您键入的字母不是“e”。
两个线程之间的通信有点类似于打乒乓球,或者至少应该如此。
下面我将添加我编写的一段代码。它还没有完成,但有一个问题我无法修复或找到解决方案。当我尝试运行此代码时,它会卡住。看起来两个线程都在等待信号,所以什么都没有发生。
怎么了?
#include <iostream>
#include <fstream>
#include <string>
#include <pthread.h>
#include <stdlib.h>
using namespace std;
pthread_mutex_t mut;
pthread_cond_t dadam;
pthread_cond_t dudum;
char x;
void *first(void *arg) {
while(1) {
pthread_mutex_lock(&mut);
pthread_cond_wait(&dadam, &mut);
cout << "Type a letter\n";
cin >> x;
pthread_mutex_unlock(&mut);
pthread_cond_signal(&dudum);
}
}
void *second(void *arg) {
while(1) {
pthread_cond_wait(&dudum, &mut);
pthread_mutex_lock(&mut);
char y;
y = toupper(x);
cout << y << endl;
pthread_mutex_unlock(&mut);
pthread_cond_signal(&dadam);
}
}
int main()
{
pthread_t nun;
pthread_t nuno;
pthread_create(&nun, NULL, &first,NULL);
pthread_create(&nuno, NULL, &second,NULL);
pthread_cond_signal(&dadam);
pthread_join(nun, NULL);
pthread_join(nuno, NULL);
return 0;
}
【问题讨论】:
-
C 和 C++ 是不同的语言,有不同的处理方法。您打算使用哪个?除了(不必要的)
using namespace std这只是 C 代码。 C++ 有std::thread来处理这个问题。 -
在您致电
pthread_cond_wait之前,您必须检查您要等待的事情是否尚未发生。在pthread_cond_wait返回后继续之前,您必须检查以确保您想要等待的事情已经发生。条件变量是无状态的,不知道您在等待什么。确保您在需要时且仅在需要时致电pthread_cond_wait是您 100% 的责任。模式是pthread_mutex_lock(...); while (something_has_not_happened_yet) pthread_cond_wait(...); ...stuff.. pthread_mutex_unlock(...);。 -
im 使用 C。之前用 c++ 尝试过,但经过多次尝试后仍然留下一些不需要的片段,老实说,我混合了我想做的和输入的内容。无论如何对不起问题,谢谢你
标签: c++ linux multithreading