#include
#include
#include
pthread_t oddThread,evenThread;
sem_t semEven,semOdd;
int counter = -1;
void *oddFn(void *arg)
{
while (counter < 15) {
sem_wait(&semOdd);
printf("Counter:%d\n",++counter);
sem_post(&semEven);
}
pthread_exit(NULL);
}
void *evenFn(void *arg)
{
while (counter < 15) {
sem_wait(&semEven);
printf("Counter:%d\n",++counter);
sem_post(&semOdd);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int ret;
sem_init(&semEven, 0, 1);
sem_init(&semOdd, 0, 0);
ret = pthread_create(&evenThread, NULL, evenFn, NULL);
if (ret != 0) {
perror("Error in creating Thread\n");
exit(1);
}
ret = pthread_create(&oddThread, NULL, oddFn, NULL);
if (ret != 0) {
perror("Error in creating Thread\n");
exit(1);
}
pthread_join(evenThread, NULL);
pthread_join(oddThread, NULL);
sem_destroy(&semEven);
sem_destroy(&semOdd);
pthread_exit(NULL);
}
Comments
Post a Comment