#include <pthread.h>
#include <stdio.h>
#define MAX 1000
#define MAX_COUNT 1500
int count = 0;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_max = PTHREAD_COND_INITIALIZER;
int thread_id[3] = {0,1,2};
void increment(int *);
void watch(int *);
int
main(int argc, char *argv[])
{
int i;
/* define the type to be pthread */
pthread_t thread[3];
/* create 3 threads*/
pthread_create(&thread[0], NULL, increment, &thread_id[0]);
pthread_create(&thread[1], NULL, increment, &thread_id[1]);
pthread_create(&thread[2], NULL, watch, &thread_id[2]);
for(i=0; i< 3 ; i++)
{
pthread_join(thread[i], NULL);
}
return 0;
}
void watch(int *id)
{
/* lock the variable */
pthread_mutex_lock(&count_mutex);
while(count <= MAX_COUNT)
{
/* using the condition variable for waiting for the event */
pthread_cond_wait(&count_max, &count_mutex);
printf("Inside the watch() and the value is %d\n", count);
}
/*unlock the variable*/
pthread_mutex_unlock(&count_mutex);
}
void increment(int *id)
{
int i;
for(i=0; i< MAX ; i++)
{
/* lock the variable */
pthread_mutex_lock(&count_mutex);
count++;
printf("in increment counter by threadof id :%d, and count"
":%d\n",*id, count);
/* for the condition notify the thread */
pthread_cond_signal(&count_max);
/*unlock the variable*/
pthread_mutex_unlock(&count_mutex);
}
}
|