我们必须编写将创建两个线程的程序。第一个线程将要求从键盘输入字母,然后它将信号发送到第二个线程,等待它。然后它将把这封信改成大写,如果这封信不是'E',它将发送另一个信号到线程1。在您键入的字母不再为'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;
}
料青山看我应如是
qq_花开花谢_0