68 lines
2.1 KiB
C
68 lines
2.1 KiB
C
|
/*
|
|||
|
编写一个程序, 创建两个线程, 一个线程负责向共享缓冲区写入数据, 另一个线程负责从缓冲区读取数据。要求实现线程间的同步和互斥, 确保读取线程只能在缓冲区有数据时才能读取, 写入线程只能在缓冲区为空时才能写入。
|
|||
|
【提示】缓冲区可以在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);
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|