编写C语言程序,模拟完成读者写者问题使用gcc编译并运行。
时间: 2024-09-27 16:08:48 浏览: 40
基于C语言和linux编译的的手机程序
在C语言中,读者写者问题是操作系统中常见的同步问题,它涉及到多个线程如何共享数据资源,避免同时读写导致的数据混乱。这里我们可以使用互斥锁(mutex)来解决这个问题。以下是一个简单的C程序示例,它创建了两个线程,一个代表读者,另一个代表写者:
```c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h> // 使用信号量来控制并发
#define MAX_READERS 5
#define MAX_WRITERS 1
#define BUFFER_SIZE 10
char buffer[BUFFER_SIZE] = {0};
int readers_in = 0, writers_in = 0;
sem_t mutex; // 互斥锁
sem_t reader_sem; // 用于限制同时进入的读者数
sem_t writer_sem; // 用于限制同时进入的写者数
void* reader(void* arg) {
while (readers_in < MAX_READERS && !writers_in) {
sem_wait(&reader_sem); // 等待读者权限
printf("Reader %d entered and read from buffer: ", pthread_self());
for (int i = 0; i < BUFFER_SIZE; ++i) {
if (buffer[i]) {
printf("%c", buffer[i]);
break;
}
}
buffer[0] = 'R'; // 读取完成后更新缓冲区
sem_post(&mutex); // 释放互斥锁
sem_post(&reader_sem); // 允许下一个读者进来
readers_in++;
}
return NULL;
}
void* writer(void* arg) {
while (!writers_in || readers_in) {
sem_wait(&writer_sem); // 等待写者权限
printf("Writer %d entered and wrote to buffer: ", pthread_self());
buffer[0] = 'W'; // 写入新的字符
sem_post(&mutex); // 释放互斥锁
sem_post(&writer_sem); // 允许下一个写者进来
writers_in++;
}
return NULL;
}
int main() {
pthread_t reader_thread, writer_thread;
int rc;
// 初始化信号量
sem_init(&mutex, 0, 1);
sem_init(&reader_sem, 0, MAX_READERS);
sem_init(&writer_sem, 0, MAX_WRITERS);
rc = pthread_create(&reader_thread, NULL, reader, NULL);
if (rc) {
perror("Error creating reader thread");
exit(EXIT_FAILURE);
}
rc = pthread_create(&writer_thread, NULL, writer, NULL);
if (rc) {
perror("Error creating writer thread");
exit(EXIT_FAILURE);
}
rc = pthread_join(reader_thread, NULL);
if (rc) {
perror("Error joining reader thread");
}
rc = pthread_join(writer_thread, NULL);
if (rc) {
perror("Error joining writer thread");
}
sem_destroy(&mutex);
sem_destroy(&reader_sem);
sem_destroy(&writer_sem);
return 0;
}
```
要编译这个程序,你可以使用`gcc -lpthread program_name.c -o program_name`命令。然后,运行程序`./program_name`。
阅读全文