LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - General
User Name
Password
Linux - General This Linux forum is for general Linux questions and discussion.
If it is Linux Related and doesn't seem to fit in any other forum then this is the place.

Notices


Reply
  Search this Thread
Old 05-08-2005, 11:58 PM   #1
linux_ujjwal
LQ Newbie
 
Registered: May 2005
Posts: 2

Rep: Reputation: 0
Difference between condition variable and mutex


I have started reading thread synchronization, after reading about the use of condition variable, i got confused with the use of mutex. Please elaborate me on this with some example. THANKYOU
 
Old 05-09-2005, 12:52 PM   #2
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
Hello,

AFIK the difference has to do with what constitutes an "atomic" operation, ie the guarantee that a variable change of state will not be interrupted between the original test of the variable, and the subsequent setting of the new state. For example:

Using a variable

Code:
static int bFlag = 0;

int thread1()
{
  //  Execute critical code
  while ( 1 ) {
    if ( !bFlag ) {
      //  Allow this thread to run and block all other threads
      bFlag = 1;    //  Change flag state to block other threads
      critical  code...

      //  Unblock and allow other threads to run
      bFlag = 0;
      break;
    }
    else {
      // Block here waiting to run
      continue;
    }
  }

   //  Non critical code
}

int thread2()
{
   //  Execute critical code
  while ( 1 ) {
    if ( !bFlag ) {
      //  Allow this thread to run and block all other threads
      bFlag = 1;    //  Change flag state to block other threads
      critical  code...

      //  Unblock and allow other threads to run
      bFlag = 0;
      break;
    }
    else {
      // Block here waiting to run
      continue;
    }
  }

  //  Non critical code
}
As you can see, each thread tests a global variable, bFlag, in order to see if it is allowed to run the critical section of code or not and each thread loops around waiting (being blocked) if the flag is TRUE (some other thread has control of the resource). The problem comes in when preemptive multi-tasking kernels are used. There is a chance the either one of the threads can be swapped out between the lines that test the global variable, and subsequently set it. Because of this time window, it is entirely possible for each thread to presume that it has set the lock and both run the critical code section. This could lead to extremely unpleasant happenings.

Using a mutex is supposed to prevent this problem by insuring that the executing thread is NOT swapped out during the internal test-and-set operation. It does this by running the test-and-set at kernel level and by making sure that the scheduler isn't run until the operation has completed. For example:

Using a mutex.

Code:
static mutex bFlag = MUTEX_FREE;

int thread1()
{
  //  Execute the critical code
  mutex_lock( &bFlag );  //  Block other threads from running

  //  If we get to here, then we have the lock and can safely run
  critical code...

  //  Unblock and continue
  mutex_free( &bFlag );

  //  Non critical code
}

int thread2()
{
  //  Execute the critical code
  mutex_lock( &bFlag );  //  Block other threads from running

  //  If we get to here, then we have the lock and can safely run
  critical code...

  //  Unblock and continue
  mutex_free( &bFlag );

  //  Non critical code
}
Since we are using a kernel supported mutex, we can safely presume that each thread will be blocked when the other thread needs to access the critical section of code.
 
Old 05-09-2005, 04:20 PM   #3
hasse69
LQ Newbie
 
Registered: May 2005
Posts: 3

Rep: Reputation: 0
I do not exactly known what you place in the term "condition variable" here, but my guess
is that you refer to e.g. a pthread conditional variable. But to me a mutex and a conditional variable
is not the same thing and have different usage. As correctly stated in the previous post mutexes has
to do with thread synchronization (simultaneous running threads) and the protection of critical code
segments (shared data). A CV on the other hand may come very useful for waking up a sleeping (blocked)
thread, e.g. signaling data availability etc. as a tool for simple inter-thread communication. This instead of
e.g. using shared memory if the destination thread is supposed to operate short-term and then go back
to sleep. Waiting on a CV is a blocking operation so the thread would only consume CPU when there
is actually data available to operate on.
So, it is a blocking operation which means that it can be compared to a select(2) waiting on data from
e.g. a pipe which may serve the same purpose.
In my opinion I prefer the pipe for this, but the only real reason for that is that if there are other things
to wait for (sockets etc) then the pipe-select better fits the design than to also involve CVs.
And, please correct me if I am wrong, a select(2) call can not be issued for a CV since the CV can not be part
of the select mask.
I have also heard rumors about some pthread implementations that is less "optimal" and select(2) is
stated to perform much better in time-critical applications. But then, it is just a rumor so please do not
take my word for it. If it is really a concern I would implement both and benchmark them against each other.
 
Old 05-10-2005, 01:41 AM   #4
foo_bar_foo
Senior Member
 
Registered: Jun 2004
Posts: 2,553

Rep: Reputation: 53
yes as stated above mutex makes operations atomic
that is whatever you need to do inside the thread you can do with a lock on a structure a variable whatever
and no other threads can toy with that structure or variable or pointers till you are done.
this doesn't have to be condition variables.

now if you want to use a condition variable to controll your thread (a flag) and others at the same time
you can put a mutex lock on the condition flag like rstewart has shown
however
if we are looking to do something when another thread set the flag we will only lock it when we check the flag
so the other thread can change it
unfurtunately you can end up with a bunch of threads doing loops and eating up cpu cycles
locking and unlocking and checking conditions like crazy waiting to do stuff. (bad)
so you figure you have to use wait
but if we try to use wait doing this we could concievable cause a race condition by fluke scheduling like before we tried mutex at all.
lets say the thread checks the flag (locks and unlocks the mutex) and it's not set. then the schedular interupts and
starts main in the middle of setting the flag. then goes back to the thread and it goes to wait in the wrong place and waits forever.

enter GNU to the rescue with
Code:
int  thread_flag = 0;
pthread_cond_t  thread_flag_condition;
pthread_mutex_t  thread_flag_mutex;


void *thread_function1 (void *thread_arg) {
  while(1) {
    pthread_mutex_lock (&thread_flag_mutex);
    while (!thread_flag)
       // now we can just hang here 
       // it's important to know this atomically unnlocks the mutex and then when signaled reaquires the lock
       pthread_cond_wait(&thread_flag_condition, &thread_flag_mutex);
     // when we get here we know someone set the flag
     pthread_mutex_unlock (&thread_flag_mutex);
     do_junk();
      // now send the other thread blocked in while (thread_flag) on it's merry way
      set_thread_flag(0);
   }
   return NULL;
}

void set_thread_flag(int flag_value) {
  pthread_mutex_lock (&thread_flag_mutex);
  thread_flag=flag_value;
  pthread_cond_signal(&thread_flag_condition);
  // nothing can check the flag till this lock is removed
  pthread_mutex_unlock (&thread_flag_mutex);
}
  
void *thread_function2 (void *thread_arg) {
  while(1) {
    pthread_mutex_lock (&thread_flag_mutex);
    while (thread_flag)
       // now we can just hang here 
       // it's important to know this atomically unnlocks the mutex and then when signaled reaquires the lock
       pthread_cond_wait(&thread_flag_condition, &thread_flag_mutex);
     // when we get here we know someone set the flag
     pthread_mutex_unlock (&thread_flag_mutex);
     do_other_junk();
      // now send the other thread blocked in while (!thread_flag) on it's merry way
      set_thread_flag(1);
   }
   return NULL;
}
 
Old 05-10-2005, 03:17 AM   #5
linux_ujjwal
LQ Newbie
 
Registered: May 2005
Posts: 2

Original Poster
Rep: Reputation: 0
Thank you

Thank you all, for elaborately explainning the difference

I was working over it for long to understand it

I think now, i can use CV properly.

Ujjwal
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
difference mutex vs. semaphore? Thinking Programming 1 11-16-2005 05:26 AM
Whats the difference between a Mutex and a Semaphore? The_Nerd Programming 3 07-07-2004 09:28 AM
If condition in script imsajjadali Red Hat 5 06-07-2004 06:52 AM
simple if condition sonesay Programming 10 05-21-2004 10:34 PM
P-thread+race condition+mutex+Peterson's algorithm bangla_linux Programming 3 10-29-2003 03:01 AM

LinuxQuestions.org > Forums > Linux Forums > Linux - General

All times are GMT -5. The time now is 11:15 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration