操作系统-读者写者问题(读者优先)

这个程序实现了读者写者问题的并发控制,使用了信号量来协调多个读者和写者的操作。读者和写者线程通过等待和发布信号量来确保互斥访问共享资源。测试数据模拟了不同线程的角色(读者或写者)及其操作时间,展示了如何在多线程环境中避免数据竞争。
摘要由CSDN通过智能技术生成
/*
*   读者优先
*/

# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <sys/types.h>
# include <pthread.h>
# include <semaphore.h>
# include <string.h>
# include <unistd.h>

//semaphores
sem_t rw, mutex;
int readCount;

struct data {
    int id;
    int opTime;
    int lastTime;
};

//读者
void* Reader(void* param) {
    int id = ((struct data*)param)->id;
    int lastTime = ((struct data*)param)->lastTime;
    int opTime = ((struct data*)param)->opTime;

    sleep(opTime);
    printf("Thread %d: waiting to read\n", id);
    sem_wait(&mutex); 
    if(readCount == 0)
        sem_wait(&rw);
	readCount++;
    sem_post(&mutex);

    printf("Thread %d: start reading\n", id);
    /* reading is performed */
    sleep(lastTime);
    printf("Thread %d: end reading\n", id);

    sem_wait(&mutex);
    readCount--;
    if(readCount == 0)
        sem_post(&rw);
    sem_post(&mutex);
    pthread_exit(0);
}

//写者
void* Writer(void* param) {
    int id = ((struct data*)param)->id;
    int lastTime = ((struct data*)param)->lastTime;
    int opTime = ((struct data*)param)->opTime;

    sleep(opTime);
    printf("Thread %d: waiting to write\n", id);
    sem_wait(&rw);

    printf("Thread %d: start writing\n", id);
    /* writing is performed */
    sleep(lastTime);
    printf("Thread %d: end writing\n", id);

    sem_post(&rw);
    pthread_exit(0);
}

int main() {
    //pthread
    pthread_t tid; // the thread identifier

    pthread_attr_t attr; //set of thread attributes

    /* get the default attributes */
    pthread_attr_init(&attr);

    //initial the semaphores
    sem_init(&mutex, 0, 1);
    sem_init(&rw, 0, 1);
    readCount = 0;

    int id = 0;
    while(scanf("%d", &id) != EOF) {

        char role;      //producer or consumer
        int opTime;     //operating time
        int lastTime;   //run time

        scanf("%c%d%d", &role, &opTime, &lastTime);
        struct data* d = (struct data*)malloc(sizeof(struct data));

        d->id = id;
        d->opTime = opTime;
        d->lastTime = lastTime;

        if(role == 'R') {
            printf("Create the %d thread: Reader\n", id);
            pthread_create(&tid, &attr, Reader, d);

        }
        else if(role == 'W') {
            printf("Create the %d thread: Writer\n", id);
            pthread_create(&tid, &attr, Writer, d);
        }
    }

    //信号量销毁
    sem_destroy(&mutex);
    sem_destroy(&rw);

    return 0;
}

读者优先测试数据:

1 R 3 5
2 W 4 5
3 R 5 2
4 R 6 5
5 W 7 3

测试结果:
读者优先

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值