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

/* cc -o pcthreads pcthreads.c -lpthread -lrt */

sem_t produced, consumed; /* semaphores */
int n;
int main(void)
{
        pthread_t idprod, idcons; /* ids of threads */
        void *produce(void *);
        void *consume(void *);
        int loopcnt = 5;

        n = 0;
        if (sem_init(&consumed, 0, 0) < 0) {
                perror("sem_init");
                exit(1);
        }
        if (sem_init(&produced, 0, 1) < 0) {
                perror("sem_init");
                exit(1);
        }
        if (pthread_create(&idprod, NULL, produce, (void *)loopcnt) != 0) {
                perror("pthread_create");
                exit(1);
        }
        if (pthread_create(&idcons, NULL, consume, (void *)loopcnt) != 0) {
                perror("pthread_create");
                exit(1);
        }
        pthread_join(idprod, NULL);
        pthread_join(idcons, NULL);
        sem_destroy(&produced);
        sem_destroy(&consumed);
        return 0;
}        

void *produce(void *arg)
{
        int i, loopcnt;
        loopcnt = (int)arg;
        for (i=0; i<loopcnt; i++) {
                sem_wait(&consumed);
                n++;  /* increment n by 1 */
                sem_post(&produced);
        }
        return NULL;
}       

void *consume(void *arg)
{
        int i, loopcnt;
        loopcnt = (int)arg;
        for (i=0; i<loopcnt; i++) {
                sem_wait(&produced);
                printf("n is %d\n", n); /* print value of n */
                sem_post(&consumed);
        }
        return NULL;
}