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

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

int main()
{
    unsigned int niters;
    pthread_t t1, t2;

    niters = 10;

    for (int i = 0; i < 10; i++)
    {
        printf("niters=%d\n", niters);
        for (int j = 0; j < 20; j++)
        {
            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);
                exit(1);
            }
            else
            {
                printf("Correct! cnt=%d\n", cnt);
            }
        }
        niters *= 10;
    }
    exit(0);
}

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

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