其他分享
首页 > 其他分享> > 【操作系统原理】【实验4】读者写者问题之读者优先

【操作系统原理】【实验4】读者写者问题之读者优先

作者:互联网

1.1 实验目的

1.2 代码

#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;
}

1.3 运行截图

标签:writeLock,操作系统,lock,pthread,写者,unlock,mutex,读者,accessReaderCnt
来源: https://www.cnblogs.com/amnotgcs/p/15556597.html