Condition variables


 
Thread Tools Search this Thread
Top Forums Programming Condition variables
# 1  
Old 12-03-2010
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:

Code:
    
pthread_mutex_lock(&count_mutex);
while (count<COUNT_LIMIT) { <--- why is this a 'while' and not an 'if' ?
    pthread_cond_wait(&count_threshold_cv, &count_mutex);
    count += 125;
 }
pthread_mutex_unlock(&count_mutex);

Why is the check for count in the while loop and not an if ?

From what I see, the only advantage of it being in the while loop is if by any chance the signaling thread incorrectly signaled the waiting thread (i.e. it sent a signal even though the value of count was still < COUNT_LIMIT). But in that case, I would expect the code to be something like this:

Code:
    
pthread_mutex_lock(&count_mutex);
while (count<COUNT_LIMIT) { 
    pthread_cond_wait(&count_threshold_cv, &count_mutex);
 }
count += 125; <--- I moved this outside of 'while'
pthread_mutex_unlock(&count_mutex);

Im probably missing something.

You can get the complete code here:
https://computing.llnl.gov/tutorials.../#ConVarSignal
# 2  
Old 12-03-2010
I think you're right. That code shouldn't be in the while loop.
# 3  
Old 12-06-2010
Look up "spurious wakeups".

The function could return for some reason other than the thread signaling the condition variable. In practice some implementations have an unrestartable pthread_cond_wait() function which could be aborted by a signal, for example. Other failure modes are possible and happen (rarely) on other systems.

In addition I believe one reason for introducing this concept was to enforce careful programming; Don't just assume the condition is implicitly true, but always make sure it really is.

Last edited by Driver; 12-06-2010 at 09:32 AM..
This User Gave Thanks to Driver For This Post:
# 4  
Old 12-06-2010
The use of a loop for pthread_cond_wait() and pthread_cond_timedwait() is regarded as good programming practice to handle spurious signals since these APIs are generally implemented using signals on Unix and GNU/Linux systems.

For example, Dave Butenhof's book gives the following example on page 79
Code:
while (data.value = 0) {
     status = pthread_cond_timedwait ( &data.cond, &data.mutex, &timeout);
     if (status == ETIMEOUT ) {
          printf ("Condition wait timed out.\n");
          break;
     } else if (status != 0)
          err_abort(status, "Wait on condition");
}

# 5  
Old 12-06-2010
Quote:
Originally Posted by Driver
Look up "spurious wakeups".

The function could return for some reason other than the thread signaling the condition variable.
It could, but it isn't checking for that! It's just adding to its own variable whenever woken no matter what. It looks wrong.
# 6  
Old 12-06-2010
It makes sense if you look at the entire example code.
See https://computing.llnl.gov/tutorials...itionVariables
This User Gave Thanks to fpmurphy For This Post:
# 7  
Old 12-07-2010
Quote:
Why is the check for count in the while loop and not an if ?
I should probably devote some times and write a nice article about it on my blog. But, as you surely know, time is a scare resource... so I will merely copy-paste the most important point of a lecture I gave on the matter:

It is a good idea to enclose the condition wait with the equivalent of a while loop that checks the predicate. This has the following advantages:
  • allow use of “loose predicate”. A rule of thumbs says: It's a lot easier to have a “loose predicate” (“it may be”) for the condition variable than using a tight predicate (“it is”) straight away.
  • robust against intercepted wakeup: After returning from pthread_cond_wait(), the predicate may still be false, because another thread has in-between already processed and reset the condition.
  • robust against spurious wakeup: the thread returns from pthread_cond_wait() even if the condvar has not been broadcast/signaled
POSIX states:
Quote:
It is important to note that when pthread_cond_[timed]wait() return without error, the associated predicate may still be false. Some implementations, particularly on a multiprocessor, may sometime cause multiple threads to wake up when the condition variable is signaled simultaneously on different processors.

It is thus recommended that a condition wait be enclosed in the equivalent of a "while loop" that checks the predicate.
spurious wakeup may sound strange; here the whole story recorded from David Butenhof about real origin of the "spurious wakeup" in the standard:
Quote:
Originally Posted by Dave Butenhof

POSIX threads were the result of a lot of tension between pragmatic hard real*time programmers and largely academic researchers.The intent was to force correct/robust code by requiring predicate loops. This was driven by the provably correct academic contingent among the "core threadies" in the working group, though I don't think anyone really disagreed with the intent once they understood what it meant.

We followed that intent with several levels of justification. The first was that "religiously" using a loop protects the application against its own imperfect coding practices. The second was that it wasn't difficult to abstractly imagine machines and implementation code that could exploit [spurious wakeup] to improve the performance of average condition wait operations through optimizing the synchronization mechanisms.

Actually, no member of the working group never proved that such an implementation exists. Spurious wakeups are the mechanism of an academic computer scientist clique to make sure that everyone had to write clean code that checked and verified predicates!

But the (perhaps) largely spurious (or at least arcanely philosophical) 'efficiency' argument went over better with the real*time people, and the real reason was usually relegated to second place in the rationale.

I've thought many times about how you might construct a correct and practical implementation that would really have spurious wakeups. I've never managed to construct an example. Doesn't mean there isn't one, though, and it makes a good story.
This User Gave Thanks to Loic Domaigne For This Post:
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. Programming

Understanding Condition variables

I am trying the understand the conditional variable concept. I went through the following site: https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables I understand that condition variables allow threads to synchronize based upon the VALUE of data. When the data acheives a particular... (2 Replies)
Discussion started by: rupeshkp728
2 Replies

7. 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

8. 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

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