Witam, mam do zrobienia program rozwiązujacy problem producent-konsument przy założeniu ze wątki konsumenta komunikuja sie z wątkami producenta za pomocą bufora jednoelementowego.
Program kompiluje (gcc -pthread -o program problem.c), ale gdy chce uruchomic program to mam bład "Naruszenie ochrony pamieci" i mam pytanie w jaki sposób moge to ominać?
Linuxa jakiego uzywam to Debian9. Oto cały kod programu:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <semaphore.h>
#define VALUE 10
int produkty; /* tylko do odczytu dla producenta i konsumenta */
struct{ /* dane wspólne dla konsumenta i producenta */
int bufor[VALUE];
sem_t mutex, nempty, nstored;
} shared;
void *producent(void *arg)
{
int i;
for(i = 0; i < produkty; i++){
sem_wait(&shared.nempty); /* oczekiwanie na min. jedno wolne miejsce w buforze */
sem_wait(&shared.mutex);
shared.bufor[i % VALUE] = i; /* zapamiętanie wartości w cyklicznym buforze */
sem_post(&shared.mutex);
sem_post(&shared.nstored); /* kolejny wpisany element */
}
return(0);
}
void *konsument(void *arg)
{
int i;
for(i = 0; i < produkty; i++){
sem_wait(&shared.nempty); /* oczekiwanie na min. jeden gotowy element w buforze */
sem_wait(&shared.mutex);
if(shared.bufor[i % VALUE] != i);
printf("bufor[%d] = %d\n", i, shared.bufor[i % VALUE]);
sem_post(&shared.mutex);
sem_post(&shared.nempty); /* kolejne wolne miejsce */
}
return(0);
}
int main(int argc, char **argv)
{
pthread_t tid_producent, tid_konsument;
if(argc != 2){
//err_quit("usage: prodcons1 <#items>");
}
produkty = atoi(argv[1]);
/* utworzenie trzech semaforów */
sem_init(&shared.mutex, 0, 1);
sem_init(&shared.nempty, 0, VALUE);
sem_init(&shared.nstored, 0, 0);
/* utworzenie jednego wątku producenta i jednego wątku konsumenta */
//set_concurrency(2);
pthread_create(&tid_producent, NULL, producent, NULL);
pthread_create(&tid_konsument, NULL, konsument, NULL);
/* oczekiwanie na zakończenie obu wątków */
pthread_join(tid_producent, NULL);
pthread_join(tid_konsument, NULL);
/* usunięcie semaforów */
sem_destroy(&shared.mutex);
sem_destroy(&shared.nempty);
sem_destroy(&shared.nstored);
exit(0);
}