Sunday, April 30, 2017

Posted by beni April 30, 2017

6 Pthread condition variable in Linux


Condition variable one type of thread synchronization mechanism.

By using condition variable we can tell one thread that when to execute.

using pthread_cond_signal pass the signal to another thread, this signal can be catch by another thread using pthread_cond_wait.


Below program
  • main thread will create two thread
  • second thread will wait on pthread_cond_wait to get signal.
  • first thread will increment the globalCount. When globalCount become 5 thread1 will send signal to thread2
  • now thread2 will get signal and add 20 to globalCount and exited from thread handler
  • then thread 1 increment the gloablCount until 15, and exited from thread handler function
PROGRAM : 
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
 
int globalCount = 0;
pthread_mutex_t mutex
;
pthread_cond_t condvar
;
 
void *t1_fun(void *arg) //thread 1 handler function
{
   
int i = 0;
   
int t_num = (int)arg;
 
   
for (i=0; i<15; i++) {
        pthread_mutex_lock
(&mutex);
        globalCount
++;
       
if (globalCount == 5) {
        pthread_cond_signal
(&condvar);
           
printf("t1_fun(): thread %d, globalCount = %d Signaled ", t_num, globalCount);
       
}
       
printf("t1_fun(): thread %d, globalCount = %d ", t_num, globalCount);
        pthread_mutex_unlock
(&mutex);
        sleep
(1);
   
}
    pthread_exit
(NULL);
}
 
void *condVar_fun(void *arg) //thread 2 handler function
{
int t_num = (int)arg;
       
   
printf("Thread %d created and running ", t_num);
    pthread_mutex_lock
(&mutex);
       
pthread_cond_wait
(&condvar, &mutex);
   
printf("condVar_fun(): Thread %d Condition signal received ", t_num);
    globalCount
+= 20;
printf("condVar_fun(): Thread %d globalCount = %d ", t_num, globalCount);
       
    pthread_mutex_unlock
(&mutex);
    pthread_exit
(NULL);
}
 
int main(int argc, char *argv[])
{
    pthread_t mythread1
;
    pthread_t mythread2
;
    pthread_attr_t myattr
;
   
void *joinResult;
   
int x = 0;
   
int t_arg = 1;
       
    pthread_attr_init
(&myattr);
    pthread_attr_setdetachstate
(&myattr, PTHREAD_CREATE_JOINABLE);
       
    pthread_mutex_init
(&mutex, NULL);
    pthread_cond_init
(&condvar, NULL);
       
   
if((pthread_create(&mythread1, &myattr, t1_fun,  (void*)t_arg) != 0)){
       
printf("Error, thread not created properly ");
       
return 1;
   
}
    t_arg
= 2;
   
if((pthread_create(&mythread2, &myattr, condVar_fun,  (void*)t_arg) != 0)){
       
printf("Error, thread not created properly ");
       
return 1;
   
}
   
    pthread_attr_destroy
(&myattr);
   
if(pthread_join(mythread1, &joinResult) != 0 ){
       
printf("Error pthread join ");
       
return 1;
   
}
   
printf("Main : Thread1 joined with result of %d ", (int)joinResult);
       
if

Search