资源简介

可以并发读,读写、写读、写写互斥,写者优先,代码已在Ubuntu11.10下编译运行通过

资源截图

代码片段和文件信息

#include
#include

#define W_NUM 5    //最大写者数
#define R_NUM 10  //最大读者数
#define MAX_NUM 10


pthread_mutex_t write_lock;      
pthread_mutex_t read_lock;    
pthread_mutex_t change_writer_num_lock;   
pthread_mutex_t chane_reader_num_lock;   

pthread_t writers[MAX_NUM];
pthread_t readers[MAX_NUM];

int writer_cnt = 0;
int reader_cnt = 0;


void *writer(void *writer_id){
int *ptr_idtask_id;
ptr_id = (int *)writer_id;
task_id = *ptr_id;

printf(“ Writer %d send write require\n“task_id);


pthread_mutex_lock(&change_writer_num_lock);
writer_cnt++;
//printf(“  %d\n“writer_cnt);
if(writer_cnt == 1){
pthread_mutex_lock(&read_lock);     //   读者将阻塞在这儿
}
pthread_mutex_unlock(&change_writer_num_lock);

pthread_mutex_lock(&write_lock);
printf(“ Writer %d begin to writing\n“task_id);
printf(“ Writer %d is writing.......\n“task_id);
sleep(1);
printf(“ Writer %d finished writing\n“task_id);
//sleep(2);
pthread_mutex_unlock(&write_lock);

pthread_mutex_lock(&change_writer_num_lock);
writer_cnt--;
//printf(“  %d\n“writer_cnt);
if(writer_cnt == 0){
pthread_mutex_unlock(&read_lock);
}
pthread_mutex_unlock(&change_writer_num_lock);
sleep(3);  

pthread_exit(NULL);
}

void *reader(void *reader_id){
int *ptr_idtask_id;
ptr_id = (int *)reader_id;
task_id = *ptr_id;

printf(“Reader %d send read require\n“task_id);

pthread_mutex_lock(&read_lock);    //readers choked here
pthread_mutex_lock(&chane_reader_num_lock);
reader_cnt++;
if(reader_cnt == 1){
pthread_mutex_lock(&write_lock);
}
pthread_mutex_unlock(&chane_reader_num_lock);
pthread_mutex_unlock(&read_lock);

printf(“Reader %d begin to reading\n“task_id);
printf(“Reader %d is reading.......\n“task_id);
sleep(1);
printf(“Reader %d finished reading\n“task_id);
//sleep(1);

pthread_mutex_lock(&chane_reader_num_lock);
reader_cnt--;
if(reader_cnt == 0){
pthread_mutex_unlock(&write_lock);
}
pthread_mutex_unlock(&chane_reader_num_lock);
sleep(3);

pthread_exit(NULL);
}

int main(){

int writer_id[MAX_NUM];
int reader_id[MAX_NUM];

pthread_mutex_init(&write_lockNULL);
pthread_mutex_init(&read_lockNULL);
pthread_mutex_init(&change_writer_num_lockNULL);
pthread_mutex_init(&chane_reader_num_lockNULL);

int i_W = 0;
int i_R = 0;

for(i_W = 0; i_W < W_NUM; i_W++){
writer_id[i_W] = i_W;
pthread_create(&writers[i_W]NULLwriter(void *)&writer_id[i_W]);
//sleep(0.5);
}
for(i_R = 0; i_R < R_NUM; i_R++){
reader_id[i_R] = i_R;
pthread_create(&readers[i_R]NULLreader(void *)&reader_id[i_R]);
//sleep(0.5);
}

    sleep(10);

    for(i_W = 0; i_W < W_NUM; i_W++){
     pthread_join(writers[i_W]NULL);
    }
    for(i_R = 0; i_R < R_NUM; i_R++){
     pthread_join(readers[i_R]NULL);
    }

return 0;

}

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     目录           0  2014-04-18 10:39  writer_reader\
     文件        2820  2014-04-18 10:37  writer_reader\main.c

评论

共有 条评论