gpt4 book ai didi

C 段错误 - 读者和作者

转载 作者:行者123 更新时间:2023-11-30 14:55:44 27 4
gpt4 key购买 nike

我正在尝试用 C 实现读者和编写者问题的变体,该变体是编写者可以是增量器或减量器,并且它们应该保持运行计数。下面是我尝试实现的代码,我收到错误“段错误(核心转储)”。我尝试调试并收到来自 gdb 的反馈 - main () 中的 #0 0x0000000000400d84。如果有人能够向我解释这一点/给我有关如何修复此错误的提示,我将不胜感激。谢谢!

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

#define WAIT 20
#define NEW 0

#define DECREMENT 0
#define INCREMENT 1

#define TIME 5
#define VALUE 1
#define COMMON 0


int readerCount = NEW;
int total = 0;
int v;
sem_t mutex;
sem_t access_data;



int increment_or_decrement() {
int d;
return d = rand() % 2;
}

void *writer(void *arg) {
int version = increment_or_decrement();

int *iID = (int *) arg;
int *dID = (int *) arg;

sleep(rand() % WAIT);

sem_wait(&access_data);

if (version == INCREMENT) {
fprintf(stderr, "Incrementer %d accessed the data\n", *iID);
total++;
fprintf(stderr, "Total: %d\n", total);
}
else {
fprintf(stderr, "Decrementer %d accessed the data\n", *dID);
total--;
fprintf(stderr, "Total: %d\n", total);
}

sleep(TIME);

sem_post(&access_data);

pthread_exit(NULL);

}


void *reader(void *arg) {
int *id = (int *) arg;

sleep(rand() % WAIT);

while(1) {
if (readerCount == NEW) {
sem_wait(&mutex);

v = version;
readerCount++;

if (readerCount == 1)
sem_wait(&access_data);

sem_post(&mutex);

fprintf(stderr, "Reader %d accessed the data\n", *id);

sem_wait(&mutex);

readerCount--;

if(readerCount == NEW)
sem_post(&access_data);

sem_post(&mutex);

pthread_exit(NULL);
}
}

}


int main() {
int numReaders = rand();
int numWriters = rand();
int i;

sem_init(&mutex, COMMON, VALUE);
sem_init(&access_data, COMMON, VALUE);

pthread_t readers[numReaders];
pthread_t writers[numWriters];

int readerID[numReaders];
int writerID[numWriters];

for (i = 0; i < numReaders; i++)
readerID[i] = i;

for (i = 0; i < numWriters; i++)
writerID[i] = i;

for (i = 0; i < numReaders; i++) {
if(pthread_create(&readers[i], NULL, reader, (void *) &readerID[i]) != 0) {
printf("Child failed\n");
exit(EXIT_FAILURE);
}
}

for (i = 0; i < numWriters; i++) {
if (pthread_create(&writers[i], NULL, writer, (void *) &writerID[i]) != 0) {
printf("Child failed\n");
exit(EXIT_FAILURE);
}
}

for (i = 0; i < numReaders; i++) {
if (pthread_join(readers[i], NULL) != 0) {
printf("Join failed\n");
exit(EXIT_FAILURE);
}
}

for (i = 0; i < numWriters; i++) {
if (pthread_join(writers[i], NULL) != 0) {
printf("Join failed\n");
exit(EXIT_FAILURE);
}
}

sem_destroy(&access_data);
sem_destroy(&mutex);
}

最佳答案

如果 rand 返回大数字(如 @WhozCraig 的评论中所示),您可能会耗尽堆栈空间

如果您只是分配一些有限值而不是在此处使用 rand:

  int numReaders = rand();
int numWriters = rand();

我看到它运行时没有段错误

关于C 段错误 - 读者和作者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603869/

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