Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c - I want to readers/writers problem with binary semaphore

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...