I have 5 writers, 20 readers.
I want to solve readers/writers problem with binary semaphore.
But my code has some problem. There is segmentation fault(core dumped).
I think that there is a problem when creating threads.
How can I solve the problem? and Is this right code to solve r/w problem?
I used my text book's pseudo code.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t mutex, rw_mutex;
int data = 0;
int readcount = 0;
void *reader(void* i)
{
int num = *((int*)i);
sem_wait(&mutex);
readcount += 1;
if(readcount == 1)
sem_wait(&rw_mutex);
sem_post(&mutex);
printf("I'm reader%d, data is %d
", num, data);
sem_wait(&mutex);
readcount -= 1;
if( readcount == 0)
sem_post(&rw_mutex);
sem_post(&mutex);
}
void *writer(void *i)
{
int num = *((int*)i);
sem_wait(&rw_mutex);
data++;
printf("I'm writer%d, data is %d
", num, data);
sem_post(&rw_mutex);
}
void main()
{
int i;
pthread_t writer[5], reader[20];
sem_init(&rw_mutex, 0, 1);
sem_init(&mutex, 0, 1);
for(i=0; i<5; i++)
pthread_create(&writer[i], NULL, writer, &i);
for(i=0; i<20; i++)
pthread_create(&reader[i], NULL, reader, &i);
for(i=0; i<5; i++)
pthread_join(writer[i], NULL);
for(i=0; i<20; i++)
pthread_join(reader[i], NULL);
printf("End
");
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…