Print even and odd numbers using synchronization mechanism in C & Linux ?

We can use synchronization mechanisms in C, specifically mutex and condition variables, to print even and odd numbers alternately. Please find below example code for the same.
        
        #include <pthread.h>
#include <stdio.h>
#include <stlib.h>
#define MAX 100
volatile int n = 0;

pthread_mutex_t mut;
pthread_cond_t cond;
void *printEven()
{
while( n < MAX)
{
pthread_mutex_lock(&mut);
while(n % 2 != 0)
{
pthread_cond_wait(&cond, &mut);
}
printf("%d ", n);
n++;
pthread_mutex_unlock(&mut);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
void *printOdd()
{
while( n < MAX)
{
pthread_mutex_lock(&mut);
while(n % 2 != 1)
{
pthread_cond_wait(&cond, &mut);
}
printf("%d ", n);
n++;
pthread_mutex_unlock(&mut);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
int main()
{
pthread_t t1;
pthread_t t2;

pthread_mutex_init(&mut, 0);
pthread_cond_init(&cond, 0);

pthread_create(&t1, 0, &printEven, NULL);
pthread_create(&t2, 0, &printOdd, NULL);

pthread_join(&t1, 0);
pthread_join(&t2, 0);

pthread_mutex_destroy(&mut);
pthread_cond_destroy(&cond);

return(0);
}

Notes : Above program prints the numbers in ascending order due to synchronization mechanism, else it may miss the order in between while running.

Output of above program:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 
95 96 97 98 99 100

Output without synchronization for the same program :
0 2 1 3 4 5 6 7 9 8 10 12 11 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 28 30
32 31 33 34 36 35 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
85 86 87 88 89 90 91 93 92 94 96 95 97 98 99


You can see without mutex both threads are not printing in synchronize order.


Previous Post Next Post

Contact Form