gpt4 book ai didi

c - 在c中使用posix信号量的读写器应用程序中的段错误

转载 作者:行者123 更新时间:2023-11-30 14:53:40 25 4
gpt4 key购买 nike

在此代码中,写入器递增数据变量,读取器打印该数据变量。任何时候只有一个写入器可以写入,但当写入器未写入数据时,所有读取器都可以打印数据。
附加的代码有时会成功运行,但有时会出现段错误错误。

读写器代码

#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);
}

最佳答案

您在访问t[10]时超出范围

int i = 10;
....
while (i != 5)
pthread_create(&t[i--], NULL, writer, NULL);

关于c - 在c中使用posix信号量的读写器应用程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com