日期:2014-05-16  浏览次数:20642 次

麻烦看一下,多线程读者写者优先问题!(小弟新学)
麻烦看一下为什么没有输出结果的,在LINUX虚拟机上面运行的!

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#define MAX 5
pthread_mutex_t rmutex;
pthread_mutex_t wmutex;
pthread_mutex_t read_db;
pthread_mutex_t write_db;

int rc=0;
int wc=0;

void read_data_base()
{
printf("reading,");
sleep(3);
}
void write_data_base()
{
printf("writing");
sleep(2);
}
void *reader(void *ptr)
{
int i;
for(i=0;i<MAX;i++)
{
pthread_mutex_lock (&rmutex);
rc=rc+1;
if(rc==1){
pthread_mutex_lock(&read_db);
}
pthread_mutex_unlock(&rmutex);
read_data_base();
pthread_mutex_lock(&rmutex);
rc=rc-1;
if(rc==0){
pthread_mutex_unlock(&read_db);
}
pthread_mutex_unlock(&rmutex);
}
pthread_exit(0);
}

void *writer(void *ptr)
{
int i;
for(i=0;i<MAX;i++)
{
pthread_mutex_lock(&wmutex);
wc=wc+1;
if(wc==1)
{
pthread_mutex_lock(&read_db);
}
pthread_mutex_unlock(&wmutex);
pthread_mutex_lock(&write_db);
write_data_base();

pthread_mutex_lock(&wmutex);
wc=wc-1;
if(wc==0)
{
pthread_mutex_unlock(&read_db);
}
pthread_mutex_lock(&write_db);
pthread_mutex_unlock(&wmutex);
}
pthread_exit(0);
}

int main()
{
pthread_mutex_init(&rmutex,0);
pthread_mutex_init(&wmutex,0);
pthread_mutex_init(&read_db,0);
pthread_mutex_init(&write_db,0);

pthread_t tid1,tid2;
pthread_create(&tid1,NULL,reader,NULL);
pthread_create(&tid2,NULL,writer,NULL);
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_mutex_destroy(&rmutex);
pthread_mutex_destroy(&wmutex);
pthread_mutex_destroy(&read_db);
pthread_mutex_destroy(&write_db);

pthread_exit((void*)pthread_self());

}


linux

------解决方案--------------------
直接一个读写锁就好了!没必要各自一个锁!太浪费!