Hi ,
Below code prints odd and even numbers using two threads.code works correctly .
But i am unable to figure out whether it works in all scenarios.
My doubtful scenario is:
Lets say evenfun
thread is invoked first when the value of count
is 2 , so the thread waits and it also acquired the lock.
as evenfun
thread waits oddfun
thread starts to execute and try to acquire the lock.
So here , oddfun
should not get the lock because the mutex is already locked by evenfun
, but this is not happening at all.
Please let me know whether my understanding is wrong , or is it because of some mutex properties.
#include <stdio.h>
#include <pthread.h>
#define MAX 20
int count =0;
void *evenfun(void *x);
void *oddfun(void *x);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int main()
{
pthread_t o_t, e_t;
pthread_create(&o_t, NULL,oddfun, NULL);
pthread_create(&e_t, NULL,evenfun, NULL);
pthread_join(o_t,NULL);
pthread_join(e_t,NULL);
return 0;
}
void *evenfun(void *x)
{
while(1) {
pthread_mutex_lock(&mutex);
if(count%2 == 0)
{
printf("count value %d, waiting in even...\n", count);
pthread_cond_wait(&cond,&mutex);
}
count++;
if( count > MAX)
{
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return NULL;
}
printf("even: %d \n", count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
void *oddfun(void *x)
{
while (1){
pthread_mutex_lock(&mutex);
if(count%2 != 0)
{
printf("count value %d, waiting in odd...", count);
pthread_cond_wait(&cond,&mutex);
}
count++;
if( count > MAX)
{
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return NULL;
}
printf("odd: %d \n", count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}