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

void *increase(void *vargp);
void *decrease(void *vargp);
int cnt = 0;
sem_t mutex;

int main(int argc, char **argv)
{
    unsigned int niters;
    pthread_t t1,t2;
    
    if (argc != 2)
    {
        printf("Usage: %s <niters>\n", argv[0]);
        exit(2);
    }
    niters = atoll(argv[1]);
    
    sem_init(&mutex, 0, 1);
    pthread_create(&t1,NULL,increase,(void *)niters);
    pthread_create(&t2,NULL,decrease,(void *)niters);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    
    if (cnt != 0)
    {
        printf("Error! cnt=%d\n", cnt);
    }
    else
    {
        printf("Correct! cnt=%d\n", cnt);
    }
    sem_destroy(&mutex);
    exit(0);
}

void *increase(void *vargp)
{
    unsigned i ,niters = (unsigned int)vargp;
    for ( i = 0; i < niters; i++)
    {
        sem_wait(&mutex);
        cnt++;
        sem_post(&mutex);
    }
    return NULL;
}

void *decrease(void *vargp)
{
    unsigned i, niters = (unsigned int)vargp;
    for ( i = 0; i < niters; i++)
    {
        sem_wait(&mutex);
        cnt--;
        sem_post(&mutex);
    }
    return NULL;
}