问题描述
我有5位作家,20位读者.我想用二进制信号量解决读写器问题.
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");
}
推荐答案
您是否检查了编译器的警告?我收到几个警告.一个例子是:
Have you checked the warnings from your compiler? I get several warnings. One example is:
问题在于,在main
中,您有一个名为reader
的数组,但是在程序中,您还有一个名为reader
的函数.因此,当您实际需要函数时,编译器(即至少是我的编译器)会使用数组.程序崩溃了.
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.
修正警告!通过重命名函数reader
和writer
或通过重命名数组.
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.
这篇关于我想用二进制信号量来解决读者/作家的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!