I want to readers/writers problem with binary semaphore

梦想的初衷 提交于 2019-12-13 10:23:56

问题


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 \n", 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\n", 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 \n");
}

回答1:


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.



来源:https://stackoverflow.com/questions/56341997/i-want-to-readers-writers-problem-with-binary-semaphore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!