Understanding Condition variables


 
Thread Tools Search this Thread
Top Forums Programming Understanding Condition variables
# 1  
Old 11-11-2011
Understanding Condition variables

I am trying the understand the conditional variable concept.
I went through the following site:
https://computing.llnl.gov/tutorials...itionVariables
I understand that condition variables allow threads to synchronize based upon the VALUE of data.
When the data acheives a particular value then it signals the condition variable.

But in such cases when we monitor a particular value of a variable then why there is a need for condition variable here?
Why cannot we use another mutex when the variable acheives the needed value?
Example shown in the above site:
This simple example code demonstrates the use of several Pthread condition variable routines. The main routine creates three threads. Two of the threads perform work and update a "count" variable. The third thread waits until the count variable reaches a specified value.
Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
 
#define NUM_THREADS  3
#define TCOUNT 10
#define COUNT_LIMIT 12
 
int     count = 0;
int     thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
 
void *inc_count(void *t) 
{
int i;
long my_id = (long)t;
 
for (i=0; i<TCOUNT; i++) {
  pthread_mutex_lock(&count_mutex);
  count++;
 
  /* 
  Check the value of count and signal waiting thread when condition is
  reached.  Note that this occurs while mutex is locked. 
  */
  if (count == COUNT_LIMIT) {
    pthread_cond_signal(&count_threshold_cv);
    printf("inc_count(): thread %ld, count = %d  Threshold reached.\n", 
           my_id, count);
    }
 
  printf("inc_count(): thread %ld, count = %d, unlocking mutex\n", 
  my_id, count);
  pthread_mutex_unlock(&count_mutex);
  /* Do some "work" so threads can alternate on mutex lock */
  sleep(1);
  }
pthread_exit(NULL);
}
 
void *watch_count(void *t) 
{
long my_id = (long)t;
 
printf("Starting watch_count(): thread %ld\n", my_id);
/*
Lock mutex and wait for signal.  Note that the pthread_cond_wait 
routine will automatically and atomically unlock mutex while it waits. 
Also, note that if COUNT_LIMIT is reached before this routine is run by
the waiting thread, the loop will be skipped to prevent pthread_cond_wait
from never returning. 
*/
pthread_mutex_lock(&count_mutex);
while (count<COUNT_LIMIT) {
  pthread_cond_wait(&count_threshold_cv, &count_mutex);
  printf("watch_count(): thread %ld Condition signal received.\n", my_id);
  count += 125;
  printf("watch_count(): thread %ld count now = %d.\n", my_id, count);
  }
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
}
 
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
 
/* Initialize mutex and condition variable objects */
pthread_mutex_init(&count_mutex, NULL);
pthread_cond_init (&count_threshold_cv, NULL);
 
/* For portability, explicitly create threads in a joinable state */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
 
/* Wait for all threads to complete */
for (i=0; i<NUM_THREADS; i++) {
  pthread_join(threads[i], NULL);
}
printf ("Main(): Waited on %d  threads. Done.\n", NUM_THREADS);
 
/* Clean up and exit */
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(NULL);
}

For instance in the example shown in the above site why cannot we use an another mutex to monitor variable "count" value?
This new mutex will be locked by the inc_count() and unlocked when variable "count" becomes to desired value.
The watch_count() thread will wait for the availibility of the mutex.
The second mutex will act as a signalling mutex to be used instead of condition variable.
I hope I am able to clearly explain the doubt.

Last edited by rupeshkp728; 11-11-2011 at 07:36 AM.. Reason: code
# 2  
Old 11-14-2011
I do not understand your confusion very well. Here is a stab at an answer that may help.

pthread_cond_t variables MUST BE USED with separate mutexes. Mutexes do not take on values like 42. Think of cond_t variables as special add-on features for mutexes that take on a value.

See this page, scroll down to condition variables.

Linux Tutorial: POSIX Threads
# 3  
Old 11-15-2011
I do not see the condition variable is holding any value.
The condition variable is manually signalled when a variable reaches a certain value.
So here why cannot we have signal using an another mutex instead of condition variable.
The other thread will be waiting for this second mutex to be released.
Is my doubt clearly explained now?
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

How to pass variables into anothother variables?

Below are three variables, which I want to pass into variable RESULT1 username1=userid poihostname1=dellsys.com port1=8080 How can I pass these variables into below code... RESULT1=$((ssh -n username1@poihostname1 time /usr/sfw/bin/wget --user=sam --password=123 -O /dev/null -q... (4 Replies)
Discussion started by: manohar2013
4 Replies

2. Shell Programming and Scripting

Passing awk variables to bash variables

Trying to do so echo "111:222:333" |awk -F: '{system("export TESTO=" $2)}'But it doesn't work (2 Replies)
Discussion started by: urello
2 Replies

3. Shell Programming and Scripting

BASH arrays and variables of variables in C++

Sometimes it is handy to protect long scripts in C++. The following syntax works fine for simple commands: #define SHELLSCRIPT1 "\ #/bin/bash \n\ echo \"hello\" \n\ " int main () { cout <<system(SHELLSCRIPT1); return 0; } Unfortunately for there are problems for: 1d arrays:... (10 Replies)
Discussion started by: frad
10 Replies

4. Shell Programming and Scripting

Running a script with multiple variables like 25 variables.

Hi All, i have a requirement where i have to run a script with at least 25 arguements and position of arguements can also change. the unapropriate way is like below. can we achieve this in more good and precise way?? #!/bin/ksh ##script is sample.ksh age=$1 gender=$2 class=$3 . . .... (3 Replies)
Discussion started by: Lakshman_Gupta
3 Replies

5. Shell Programming and Scripting

If condition return 0 even when it fails to satisfy te condition

HI My doubt may be basic one but I need to get it clarified.. When i use "if" condition that checks for many AND, OR logical conditions like if ]; then return 0 fi Even the if condition fails it returns as zero.. Any clue.. But if i add else condition like if ]; ... (2 Replies)
Discussion started by: Priya Amaresh
2 Replies

6. Shell Programming and Scripting

redirect stdout echo command in condition A run in condition B

hi, I have some problems in my simple script about the redirect echo stdout command inside a condition. Why is the echo command inside the elif still execute in the else command Here are my simple script After check on the two diff output the echo stdout redirect is present in two diff... (3 Replies)
Discussion started by: jao_madn
3 Replies

7. HP-UX

Difference between [condition] and [[condition]] and ((condition)) when used with if condition

Executed the following if conditions .. and got different results . only (( )) gave correct o/p with all scenarios . Can anybody please let me know what is the difference between and ] and ((condition)) when used with if condition. And why each condition gave different result. 1.... (2 Replies)
Discussion started by: soumyabubun
2 Replies

8. Programming

Condition variables

Hi, I am reading through the pthreads tutorial and had a question on the example they have given for condition variables. Here is the code snippet: This is what the thread waiting on the condition variables doing: pthread_mutex_lock(&count_mutex); while (count<COUNT_LIMIT) { <---... (10 Replies)
Discussion started by: the_learner
10 Replies

9. UNIX for Dummies Questions & Answers

pthread condition variables and mutexes?

I am trying to understand the exact difference between condition variables and mutexes in thread synchronization ?. I know mutex will control the thread access to shared data and condition variables will be useful for waiting for certain event or condition to occur . But I couldn't understand why... (2 Replies)
Discussion started by: siddaonline
2 Replies

10. Programming

How to convert byteArray variables to HexaString variables for Linux?

Hello everybody, I am having problem in converting byte array variables to Hexa String variables for Linux. I have done, converting byte array variables to Hexa String variables for Windows but same function doesn't work for linux. Is there any difference in OS ? The code for Windows is given... (2 Replies)
Discussion started by: ritesh_163
2 Replies
Login or Register to Ask a Question