一、代码实现
读者进程和写者进程如下:
Main.cpp
#include <pthread.h>
#include <sys/types.h>
#include <semaphore.h>
#include <unistd.h>
#include "buffer.h"
#include "deal.h"
#define MAX 20
struct sto{
sem_t mutex;
sem_t wrt;
};
struct sto shared;
int readcount;
void *Read(void *arg)
{
Instruction *ins = (Instruction*)arg;
sleep(ins->start);//等待一段时间,开始申请资源
//有读者请求资源,则读者数目加1
//判断是否有写者在使用共享数据段,有的话,等待
sem_wait(&shared.mutex);
readcount++;
if(readcount == 1) sem_wait(&shared.wrt);
sem_post(&shared.mutex);
//开始读取共享数据段
cout<<"Reader "<<ins->serial_num<<" is reading."<<endl;
sleep(ins->last);
cout<<"Reader "<<ins->serial_num<<" end reading."<<endl;
//读取完毕后,读者数目减去1。
//只有全部读者读取完毕后,唤醒写者线程
sem_wait(&shared.mutex);
readcount--;
if(readcount == 0) sem_post(&shared.wrt);
sem_post(&shared.mutex);
return(NULL);
}
void *Write(void *arg)
{
Instruction *ins = (Instruction*)arg;
sleep(ins->start);
//写者读取共享数据段
sem_wait(&shared.wrt);
cout<<"Writer "<<ins->serial_num<<" is writing."<<endl;
sleep(ins->last);
cout<<"Writer "<<ins->serial_num<<" end writing."<<endl;
sem_post(&shared.wrt);
return(NULL);
}
int main()
{
FILE *fp;
char file[MAX];
int i;
pthread_t tid_read;
pthread_t tid_write;
Instruction *ins = new Data();
sem_init(&shared.mutex, 0, 1);
sem_init(&shared.wrt, 0, 1);
readcount = 0;
fp = fopen("test.txt", "r");
while(fgets(file, MAX, fp)){
ins = Deal(file);
if(ins->character == 'R'){
pthread_create(&tid_read, NULL, Read, (void*)ins);
}
else{
pthread_create(&tid_write, NULL, Write, (void*)ins);
}
/*cout<<ins->serial_num<<" "<<ins->character<<" ";
cout<<ins->start<<" "<<ins->last<<" ";
cout<<endl;*/
}
sem_destroy(&shared.mutex);
sem_destroy(&shared.wrt);
sleep(50);
return 0;
}
为了便于测试,完成以下两段辅助代码:
deal.h
#ifndef DEAL_H_
#define DEAL_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct Data{
Data(){
serial_num = 0;
character = ' ';
start = 0;
last = 0;
}
int serial_num;
char character;
int start;
int last;
} Instruction;
Instruction *Deal(char file[]);
#endif
deal.cpp
#include "deal.h"
Instruction *Deal(char file[]){
Instruction *ins = new Data();
int i;
int j = 0;
string tmp = "";
int len = strlen(file);
for(i = 0; i < len; i++){
if(file[i] != ' ' && file[i] != '\n')
tmp += file[i];
else{
if(tmp != ""){
switch(j){
case 0: ins->serial_num = atoi(tmp.c_str());
tmp = "";
break;
case 1: ins->character = tmp.at(0);
tmp = "";
break;
case 2: ins->start = atoi(tmp.c_str());
tmp = "";
break;
case 3: ins->last = atoi(tmp.c_str());
tmp = "";
break;
}
j++;
}
}
}
return ins;
}
二、测试数据及结果
测试数据文件包括n行测试数据,分别描述创建的n个线程是读者还是写者,以及读写操作的开始时间和持续时间。每行测试数据包括四个字段,各个字段间用空格分隔。第一字段为一个正整数,表示线程序号。第二字段表示相应线程角色,R表示读者,W表示写者。第三字段为一个正数,表示读写操作的开始时间:线程创建后,延迟相应时间(单位为秒)后发出对共享资源的读写申请。第四字段为一个正数,表示读写操作的持续时间。当线程读写申请成功后,开始对共享资源的读写操作,该操作持续相应时间后结束,并释放共享资源。例如:
1 R 3 5
2 W 4 5
3 R 5 2
4 R 6 5
5 W 7 3
测试结果: