|
以下程序可以运行,但原来我的意图是用读写锁实现的(现在用互斥锁实现),并用pthread_delay_up(&delay);实现线程延时的;用cc a.c -pthread -o a执行(没加注释//的是原来实现的程序);
错误有:1.8:`PTHREAD_RWLOCK_INITIALIZER' undeclared here (not in a function);
2.:11: parse error before '.' token
等
望高手指正,万分感谢
#include <pthread.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t rwpter=PTHREAD_MUTEX_INITIALIZER;
//pthread_rwlock_t rwpter=PTHREAD_RWLOCK_INITIALIZER;
int count=0;
int iprint=0;
int flag=0;
//struct timespec delay;
//delay.tv_nec=0;
void *reader(void *);
void *writer(void *);
int main()
{
int i,j;
pthread_t tid_reader[3];
pthread_t tid_writer[2];
//rrwrw
for(i=0;i<2;i++)
{
pthread_create(&tid_reader,NULL,reader,NULL);
}
pthread_create(&tid_writer[0],NULL,writer,NULL);
pthread_create(&tid_reader[2],NULL,reader,NULL);
for(i=0;i<3;i++)
{
pthread_join(tid_reader,NULL);
}
for(i=0;i<2;i++)
{
pthread_join(tid_writer,NULL);
}
exit(0);
}
void *reader(void *arg)
{
pthread_mutex_lock(&mutex);
while(flag!=0)
pthread_cond_wait(&cond,&mutex);
count++;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&rwpter);
// pthread_rwlock_rdlock(&rwpter);
printf("%d readers are reading,iprint is %d.\n",count,iprint);
// pthread_rwlock_unlock(&rwpter);
pthread_mutex_unlock(&rwpter);
int t=rand()%10;
printf("The reader will read for %d s.\n",t);
sleep(t);
// delay.tv_sec=rand();
// printf("The reader will read for %d s.\n",delay.tv_sec);
// pthread_delay_up(&delay);
pthread_mutex_lock(&mutex);
count--;
if(count==0)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("a reader is leaving and only %d readers now.\n",count);
return(NULL);
}
void *writer(void *arg)
{
pthread_mutex_lock(&mutex);
flag=1;
while(count!=0)
{
printf("The writer is waiting.\n");
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_lock(&rwpter);
// pthread_rwlock_wrlock(&rwpter);
iprint++;
printf("a writer is writing while readers %d and iprint is %d.\n",count,iprint);
// delay.tv_sec=rand();
// printf("The writer will write for %d s.\n",delay.tv_sec);
// pthread_delyay_up(&delay);
// pthread_unlock(&rwpter);
int t=rand()%10;
printf("The writer will write for %d s.\n",t);
sleep(t);
pthread_mutex_unlock(&rwpter);
flag=0;
pthread_mutex_unlock(&mutex);
printf("The writer is leaving.\n");
pthread_cond_broadcast(&cond);
return(NULL);
} |
|