PTHREADS Deadlock Erzeuger-Verbraucher
-
28-09-2019 - |
Frage
Ich schrieb folgenden Code:
void *produce(void* arg)
{
buffer* buff = (buffer *) arg;
while (1)
{
pthread_mutex_lock(&mutex);
if (elements_produced == JOB_SIZE)
{
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
elements_produced++;
while (buff->in_buff == CAPACITY)
{
pthread_cond_wait(&cond_empty, &mutex);
}
// produce
buff->buffer[buff->tail] = rand();
sum_produced += buff->buffer[buff->tail];
printf(">produced %d\n", buff->buffer[buff->tail]);
buff->tail = (buff->tail + 1) % CAPACITY;
buff->in_buff++;
pthread_cond_signal(&cond_empty);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *consume(void* arg)
{
int rc;
buffer* buff = (buffer *) arg;
while (1)
{
rc = pthread_mutex_lock(&mutex);
if (elements_consumed == JOB_SIZE)
{
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
return 0;
}
elements_consumed++;
while (buff->in_buff == 0)
{
rc = pthread_cond_wait(&cond_empty, &mutex);
}
// consume
printf("<consumed %d\n", buff->buffer[buff->head]);
sum_consumed += buff->buffer[buff->head];
buff->head = (buff->head + 1) % CAPACITY;
buff->in_buff--;
pthread_cond_signal(&cond_full);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
return 0;
}
Alle Variablen werden korrekt initialisiert. Die Aufgabe ist JOB_SIZE Elemente zu produzieren und zu konsumieren. Von Zeit zu Zeit wird es in der Riegelschloss stecken. Ich bin ganz neu in den Posix-Threads so dass ich wahrscheinlich etwas sehr offensichtlich fehle (tat Produzenten / Konsumenten oft in Java / C # / Python, aber jetzt bin ich wirklich stecken). Ich weiß, dass es viel einfacher ist es mit Semaphore zu tun, aber ich brauche es auf diese Weise zu tun.
Irgendwelche Vorschläge?
Lösung
verwendet Sie cond_empty auf beiden Seiten für die Wartezeit. Sie signalisieren (aber nie warten) cond_full.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow