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

70 lines
2.2 KiB
C
Raw Normal View History

/*
, 线, 线, 线线, 线, 线
main函数中创建char , 线
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
int buffer_empty = 1; // 缓冲区是否为空的标志,初始为空
void *w_thread(void *data)
{
char *str = (char *)data;
pthread_rwlock_wrlock(&rwlock); // 获取写入锁
while (!buffer_empty) // 当缓冲区非空时,释放锁,等待 1 毫秒再次尝试获取写入锁
{
pthread_rwlock_unlock(&rwlock); // 释放写入锁
usleep(1000); // 等待缓冲区为空
pthread_rwlock_wrlock(&rwlock); // 再次获取写入锁
}
printf("请输入内容:");
fflush(stdout); // 刷新输出缓冲
scanf("%s", str);
buffer_empty = 0; // 缓冲区非空
pthread_rwlock_unlock(&rwlock); // 释放写入锁
return NULL;
}
void *r_thread(void *data)
{
char *str = (char *)data;
pthread_rwlock_rdlock(&rwlock); // 获取读取锁
while (buffer_empty) // 当缓冲区为空时释放锁等待1毫秒缓冲区非空后(等待写缓冲区线程写入内容),再次获取锁,直到判断非空,在进行后续打印
{
pthread_rwlock_unlock(&rwlock); // 释放读取锁
usleep(1000); // 等待缓冲区非空
pthread_rwlock_rdlock(&rwlock); // 再次获取读取锁
}
printf("输入的内容为: %s\n", str);
buffer_empty = 1; // 缓冲区为空
pthread_rwlock_unlock(&rwlock); // 释放读取锁
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_rwlock_destroy(&rwlock); // 销毁读写锁
return 0;
}