In this blog we are going to learn how to use pthread condition variable. Condition variables allow threads to wait until some event or condition has occurred. Let us see an example.

#define ARR_SIZE 10

int arr[ARR_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Write a two thread functions such that one thread function will print only even numbers and another thread function will print odd numbers. Your program must ensure that all even numbers would be printed first.

How to use pthread condition variable Sample program

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

#define ARR_SIZE 10

int arr[ARR_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

pthread_mutex_t loc = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
int finished = 0;

void *foo_odd(void *arg) {
	for (;;) {
		pthread_mutex_lock(&loc);

		while (!finished) {
			// wait on mutex until signaled by foo_even
			pthread_cond_wait(&condition_var, &loc);
		}

		int i;
		for (i = 0; i < ARR_SIZE; i++) {
			if (arr[i] % 2 != 0)
				printf("%d\n", arr[i]);
		}
		pthread_mutex_unlock(&loc);
		if (i >= ARR_SIZE)
			return (NULL);
	}
}

void *foo_even(void *arg) {
	for (;;) {
		int i = 0;
		// Lock mutex and then wait for signal to relase mutex
		pthread_mutex_lock(&loc);

		for (i = 0; i < ARR_SIZE; i++) {
			if (arr[i] % 2 == 0)
				printf("%d\n", arr[i]);
		}
		finished = 1;
		// signal to end waiting on mutex loc
		pthread_cond_signal(&condition_var);

		pthread_mutex_unlock(&loc);
		if (i >= ARR_SIZE)
			return (NULL);
	}
}

int main() {
	int res;

	pthread_t tid[2];

	res = pthread_create(&tid[0], NULL, foo_even, NULL);
	if (res) {
		printf("thread creation failed\n");
		exit(-1);
	}

	res = pthread_create(&tid[1], NULL, foo_odd, NULL);
	if (res) {
		printf("thread creation failed\n");
		exit(-1);
	}

	int i = 0;
	for (i; i < 2; i++){
		pthread_join(tid[i], NULL);
	}

	return 0;
}

compile and run ( sample.c )

  • Open Linux terminal and type command
  • gcc sample.c -lpthread -o sample
  • Run using ./sample
bosch@bosch-Inspiron-N5050:$ ./sample 
2
4
6
8
10
1
3
5
7
9

Ref:

https://www.cs.nmsu.edu/~jcook/Tools/pthreads/pthread_cond.html



Related Contents to follow