zoukankan      html  css  js  c++  java
  • 【操作系统原理】【实验4】读者写者问题之读者优先

    一、实验目的

    通过读者—写者例子,熟悉、掌握互斥同步编程。

    二、实验内容

    模拟实现读者—写者例子,当有读者在读,允许其他读者读;没有读者读,允许写者写;有写者写,则不允许读者读。读者和写者是两个独立的线程,要求实现读者优先,即当有读者在读时,后续读者可以读,当最后一个读者读完才允许写者写,读者和写者线程需要互斥

    三、实验代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    #define N_WRITER 5  // writer count
    #define N_READER 9  // reader count
    #define W_SLEEP 1  // writer sleep
    #define R_SLEEP 1  // reader sleep
    
    // pthread type wid array, rid array
    pthread_t wid[N_WRITER], rid[N_READER];
    // Only one person can write
    pthread_mutex_t writeLock = PTHREAD_MUTEX_INITIALIZER;
    // Only one person can access readerCnt in the same time.
    pthread_mutex_t accessReaderCnt = PTHREAD_MUTEX_INITIALIZER;
    
    int data = 0;
    int readerCnt = 0;
    
    void write()
    {
    	int rd;
    	rd = rand() % 1000;
    	printf("write %d\n", rd);
    	data = rd;
    }
    
    void read()
    {
    	printf("read %d\n", data);
    }
    
    void *writer()
    {
    	while (1) {
    		// lock the writeLock
    		pthread_mutex_lock(&writeLock);
    		write();
    		// unlock the writeLock
    		pthread_mutex_unlock(&writeLock);
    		sleep(W_SLEEP);
    	}
    	pthread_exit((void *)0);
    }
    
    void *reader(void *in)
    {
    	while (1) {
    		// lock the accessReaderCnt for increase
    		pthread_mutex_lock(&accessReaderCnt);
    		// increase reader count
    		readerCnt++;
    		if (readerCnt == 1) {
    			// lock the writeLock when the readerCnt equals one
    			pthread_mutex_lock(&writeLock);
    		}
    		// unlock the accessReaderCnt
    		pthread_mutex_unlock(&accessReaderCnt);
    
    		// output the data value
    		read();
    
    		// lock the accessReaderCnt
    		pthread_mutex_lock(&accessReaderCnt);
    		// decrease reader count
    		readerCnt--;
    		if (readerCnt == 0) {
    			// unlock the writeLock
    			pthread_mutex_unlock(&writeLock);
    		}
    		// unlock the accessReaderCnt
    		pthread_mutex_unlock(&accessReaderCnt);
    
    		sleep(R_SLEEP);
    	}
    }
    
    int main(void)
    {
    	int i = 0;
    	// create N_READER pthread for reader
    	for (i = 0; i < N_READER; i++) {
    		pthread_create(&rid[i], NULL, reader, NULL);	
    	}
    	// create N_WRITER pthread for writer
    	for (i = 0; i < N_WRITER; i++) {
    		pthread_create(&wid[i], NULL, writer, NULL);	
    	}
    	// sleep the main thread
    	while (1) {
    		sleep(10);
    	}
    	return 0;
    }
    
    

    运行截图

    有了计划记得推动,不要原地踏步。
  • 相关阅读:
    王健林:在中国远离政府太假了 期望王思聪稳重
    科目二很难考吗?经验全在这里!
    HTTP 的长连接和短连接
    JS中实现字符串和数组的相互转化
    Maven介绍,包括作用、核心概念、用法、常用命令、扩展及配置
    kafka数据可靠性深度解读
    深入浅出JMS(二)--ActiveMQ简单介绍以及安装
    ActiveMQ入门实例
    activemq的几种基本通信方式总结
    mysql按年度、季度、月度、周、日SQL统计查询
  • 原文地址:https://www.cnblogs.com/amnotgcs/p/15556597.html
Copyright © 2011-2022 走看看