I thought of using static variables for shared data and maximum limit.
I am trying to figure out possible scenarios where this can be used in real time. Please help me for that.
Code :
#include<stdio.h>
#include<pthread.h>
pthread_mutex_t pmLock;
static int shared = 0;
static int limit = 10;
void* printEven(){
printf("This is printEven() start.\n");
pthread_mutex_lock(&pmLock);
while(shared <= limit){
if(shared%2 == 0){
printf("Even:%d\n",shared);
shared++;
}
pthread_mutex_unlock(&pmLock);
}
printf("This is printEven() End.\n");
}
void* printOdd(){
printf("This is printOdd() start.\n");
pthread_mutex_lock(&pmLock);
while(shared <= limit){
if(shared%2 != 0){
printf("Odd:%d\n",shared);
shared++;
}
pthread_mutex_unlock(&pmLock);
}
printf("This is printOdd() End.\n");
}
int main(){
//init mutex lock.
if (pthread_mutex_init(&pmLock, NULL) != 0) {
printf("\n mutex init has failed\n");
return 1;
}
pthread_t thread_ids[2];
printf("Before Thread\n");
pthread_create(&thread_ids[0], NULL, printEven, NULL);
pthread_create(&thread_ids[1], NULL, printOdd, NULL);
pthread_join(thread_ids[0], NULL);
pthread_join(thread_ids[1], NULL);
printf("After Thread\n");
// destroy mutex
pthread_mutex_destroy(&pmLock);
return 0;
}