Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

Have you checked the warnings from your compiler? I get several warnings. One example is:

warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default] pthread_create(&reader[i], NULL, reader, &i);

The problem is that in main you have an array with the name reader but in the program you also have a function named reader. So the compiler (i.e. at least my compiler) use the array when you actually want the function. And the program crash.

Fix the warnings! Either by renaming the functions reader and writer or by renaming the arrays.

After that I don't see a program crash anymore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...