Program involving threads in C

0

Basically, I have a program that has two threads: adicionar and remover .

Both manipulate an integer variable called quantity.

If quantidade reaches the value 10, the thread adicionar enters the suspended state and waits for the thread remover to re-execute.

When it equals 0, the thread remover suspend expects the thread adicionar to re-execute.

Here's my code:

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


pthread_t add, rem;

unsigned int quantidade;

pthread_cond_t cond_add;
pthread_cond_t cond_rem;
pthread_mutex_t mutex;


void *adicionar(void *s)
{
    pthread_mutex_lock(&mutex);

/*quando quantidade for igual a 10, a thread vai para o estado de suspensa*/
while(quantidade == 10)
{
    printf("[AGUARDANDO] Disponiveis: %d\n", quantidade);
    pthread_mutex_unlock(&mutex);
    pthread_cond_wait(&cond_add, NULL);
    pthread_exit(&add);
};

    quantidade++;
    pthread_cond_signal(&cond_rem);
    printf("[ADICIONANDO] Disponiveis: %d\n", quantidade);
    pthread_mutex_unlock(&mutex);
    pthread_exit(&add);
}


void *remover(void *s)
{
    pthread_mutex_lock(&mutex);
    /*quando quantidade for igual a 0, a thread entra no estado de suspensa */
    while(quantidade == 0)
    {
        printf("[AGUARDANDO] Disponiveis: %d\n", quantidade);
        pthread_mutex_unlock(&mutex);
        pthread_cond_wait(&cond_rem, NULL);
        pthread_exit(&rem);
    };
    quantidade--;
    pthread_cond_signal(&cond_add);
    printf("[REMOVENDO] Disponiveis: %d\n", quantidade);
    pthread_mutex_unlock(&mutex);
    pthread_exit(&rem);
    }




int main()
{
    int i;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond_add, NULL);
    pthread_cond_init(&cond_rem, NULL);

    for(i=0;;i++)
    {
        pthread_create(&add, 0, adicionar, 0);
    }

    for(i=0;;i++)
    {
        pthread_create(&rem, 0, remover, 0);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond_add);
    pthread_cond_destroy(&cond_rem);

}

When you run the program, it runs the threads a few times and then stops working. And condition variables do not work.

If anyone can help, I will be very grateful! Tkx

    
asked by anonymous 29.04.2018 / 17:10

0 answers