qfedu-linux-advanced-level/day7/homework/h2_2.c

67 lines
1.6 KiB
C
Raw Permalink Normal View History

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int buffer_empty = 1; // 缓冲区是否为空的标志,初始为空
void *w_thread(void *data)
{
char *str = (char *)data;
pthread_mutex_lock(&mutex); // 获取互斥锁
while (!buffer_empty) // 当缓冲区非空时,等待条件变量被唤醒
{
pthread_cond_wait(&cond, &mutex);
}
printf("请输入内容:");
fflush(stdout); // 刷新输出缓冲
scanf("%s", str);
buffer_empty = 0; // 缓冲区非空
pthread_cond_signal(&cond); // 唤醒等待的读取线程
pthread_mutex_unlock(&mutex); // 释放互斥锁
return NULL;
}
void *r_thread(void *data)
{
char *str = (char *)data;
pthread_mutex_lock(&mutex); // 获取互斥锁
while (buffer_empty) // 当缓冲区为空时,等待条件变量被唤醒
{
pthread_cond_wait(&cond, &mutex);
}
printf("输入的内容为: %s\n", str);
buffer_empty = 1; // 缓冲区为空
pthread_cond_signal(&cond); // 唤醒等待的写入线程
pthread_mutex_unlock(&mutex); // 释放互斥锁
return NULL;
}
int main(int argc, char const *argv[])
{
char str[100];
pthread_t t1, t2;
pthread_create(&t1, NULL, w_thread, (void *)str);
pthread_create(&t2, NULL, r_thread, (void *)str);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_cond_destroy(&cond); // 销毁条件变量
pthread_mutex_destroy(&mutex); // 销毁互斥锁
return 0;
}