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

pthread_mutex_t mutex[2];
pthread_t* thread_id;

int even_count = 1;
int odd_count = 0;

void* thread(void* arg)
{
    int id = (int)arg+1;
    int sleep_time = rand()%9+1;
    printf("Thread %d sleeping for %d seconds\n", id, sleep_time);
    // usleep(sleep_time*1000000);
    if(id%2==0)
    {
        pthread_mutex_lock(mutex);
        printf("Thread %d is even ", id);
        even_count*=id;
        printf("and even_count is %d\n", even_count);
        pthread_mutex_unlock(mutex);
    }
    else
    {
        pthread_mutex_lock(mutex+1);
        printf("Thread %d is odd ", id);
        odd_count+=id;
        printf("and odd_count is %d\n", odd_count);
        pthread_mutex_unlock(mutex+1);
    }
    return NULL;
}


int main(int argc, char *argv[])
{
    int n;
    srand(time(NULL));
    printf("Enter the number of threads: ");
    scanf("%d", &n);
    thread_id = (pthread_t*)malloc(sizeof(pthread_t)*n);
    pthread_mutex_init(mutex, NULL);
    pthread_mutex_init(mutex+1, NULL);
    for(int i=0; i<n; i++)
    {
        pthread_create(thread_id+i, NULL, thread, (void*)i);
    }
    for(int i=0; i<n; i++)
    {
        pthread_join(*(thread_id+i), NULL);
    }
    printf("Even count is %d\n", even_count);
    printf("Odd count is %d\n", odd_count);
    pthread_mutex_destroy(mutex);
    pthread_mutex_destroy(mutex+1); 
    free(thread_id);
    return 0;
}