The problem is to print odd and even number by using two threads respectively
#include <stdlib.h> #include <string.h> #include <pthread.h> #include <string.h> #include <stdio.h> #define MAX 10 pthread_cond_t cond_var =PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int count =1; void *odd_fun(void *arg) { while(count<MAX) { pthread_mutex_lock(&lock); while( count % 2 ==0) pthread_cond_wait(&cond_var, &lock); printf("\n Odd thread creation %d\n", count); count++; pthread_cond_signal(&cond_var); pthread_mutex_unlock(&lock); } } void *even_fun(void *arg) { while(count<MAX) { pthread_mutex_lock(&lock); while( count % 2 !=0) pthread_cond_wait(&cond_var, &lock); printf("\n Even thread printing: %d \n", count); count++; pthread_cond_signal(&cond_var); pthread_mutex_unlock(&lock); } } int main() { pthread_t th_id[2]; int res = pthread_create(&th_id[0], 0, odd_fun, 0); if(res) { printf("\n Thread creation failed: %s\n", strerror(res)); exit(0); } res = pthread_create(&th_id[1], 0, even_fun, 0); if(res) { printf("\n Thread creation failed: %s\n", strerror(res)); exit(0); } pthread_join(th_id[0], NULL); pthread_join(th_id[1], NULL); return 0; }
Output:
Odd thread creation 1 Even thread printing: 2 Odd thread creation 3 Even thread printing: 4 Odd thread creation 5 Even thread printing: 6 Odd thread creation 7 Even thread printing: 8 Odd thread creation 9 Even thread printing: 10 ...Program finished with exit code 0 Press ENTER to exit console.
Related Posts:
Relevant Post:
Categories: Operating system (OS)
Leave a Reply