#include <stdio.h>
#include <pthread.h>
#include "inc.h"

enum {
    num_threads = 2
};

typedef struct {
    int x;
#if PROTECTION == 1
    pthread_mutex_t mut;
#endif
} data_t;

#if PROTECTION == 1
static void data_init(data_t *d)
{
    pthread_mutex_init(&d->mut, NULL);
}

static void data_destroy(data_t *d)
{
    pthread_mutex_destroy(&d->mut);
}
#endif

static void *worker(void *data)
{
    data_t *d = data;

    printf("%d\n", d->x);
#if PROTECTION == 1
    pthread_mutex_lock(&d->mut);
#endif
    d->x = inc(d->x);
#if PROTECTION == 1
    pthread_mutex_unlock(&d->mut);
#endif
    printf("%d\n", d->x);

    return NULL;
}

int main()
{
    int i;
    data_t d;
    pthread_t t[num_threads];
#if PROTECTION == 1
    data_init(&d);
#endif

    d.x = 5;
    for (i = 0; i < num_threads; i++)
        pthread_create(&t[i], NULL, worker, &d);

    for (i = 0; i < num_threads; i++)
        pthread_join(t[i], NULL);

#if PROTECTION == 1
    data_destroy(&d);
#endif
    return 0;
}
