使用posix信号量进行读写器应用中的分段错误

时间:2017-11-03 07:26:03

标签: c pthreads semaphore readerwriterlock

在此代码中,writer增量数据变量和reader打印此数据变量。只有一个作者可以随时写,但是当作者没有写入数据时,所有读者都可以打印数据。附加的代码有时成功运行,但有时它会给出分段错误。

读写器代码

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<stdlib.h>
#include<unistd.h>

int reader_count;
int data = 10; /* data on which writer write update & reader read */

/* sem_write: to isolate reader & writer thread */
sem_t sem_write;
/* sem_read: to increment reader counter & sem_write */
sem_t sem_read;


void *writer(void *arg);
void *reader(void *arg);

int main(void)
{
    pthread_t t[10];
    int i = 10;

    if (sem_init(&sem_read, 0, 1)) 
        exit(1);
    if (sem_init(&sem_write, 0, 1)) 
        exit(1);

    /* 5 writer create */
    while (i != 5)
        pthread_create(&t[i--], NULL, writer, NULL);
    /* 5 reader create */
    while (i)
        pthread_create(&t[i--], NULL, reader, NULL);

    /* wait for all threads to completed */
    while (i != 10)
        pthread_join(t[i++], NULL);

    sem_destroy(&sem_read);
    sem_destroy(&sem_write);
    return 0;
}

void *writer(void *arg)
{
    sem_wait(&sem_write);
    sleep(1);   /* writing work */
    data++;
    sem_post(&sem_write);
    pthread_exit(NULL);
}

void *reader(void *arg)
{
    sem_wait(&sem_read);
    reader_count++;
    if (reader_count == 1)
        sem_wait(&sem_write);
    sem_post(&sem_read);

    sleep(1);   /* reading work */
    printf("Data: %d\n", data);

    sem_wait(&sem_read);
    reader_count--;
    if (!reader_count)
        sem_post(&sem_write);
    sem_post(&sem_read);
    pthread_exit(NULL);
}

1 个答案:

答案 0 :(得分:1)

访问t[10]

时,您将离开界限
int i = 10;
....
 while (i != 5)
    pthread_create(&t[i--], NULL, writer, NULL);