描述
在键盘按一下一个键值后主线程阻塞,再一下按下一个键值则唤醒主线程。
代码
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static flags = 0;
static temp = 0;
void *KeyListen(void *arg)
{
system("stty -icanon");
while ( getchar() ) {
if ( temp % 2 ) {
temp ++;
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
flags = 0;
pthread_mutex_unlock(&mutex);
}
else {
temp ++;
pthread_mutex_lock(&mutex);;
flags = 1;
pthread_mutex_unlock(&mutex);
}
}
}
int main()
{
int retVal,i = 1;
pthread_t tid;
retVal = pthread_create(&tid,NULL,KeyListen,NULL);
if (retVal != 0) {
printf("pthread_create fail!!!\n");
exit(1);
}