Thread: pthread_cond_wait for binary semaphores

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    127

    pthread_cond_wait for binary semaphores

    Are there any known algorithms for simulating pthread_cond_wait when using semaphores instead of mutexes?

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by homer_3 View Post
    Are there any known algorithms for simulating pthread_cond_wait when using semaphores instead of mutexes?
    A semaphore with an initial count of 1 is the same as a mutex.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Quote Originally Posted by homer_3 View Post
    Are there any known algorithms for simulating pthread_cond_wait when using semaphores instead of mutexes?
    The only difference between using a semaphore and pthread_cond_wait is that signaling a semaphore will allow the next thread through even if there is not a thread currently blocking. pthread_cond_signal does nothing if no thread is waiting on a call to pthread_cond_wait.

    So instead of just calling sem_post instead of pthread_cond_signal, you have to do something like this:

    Code:
    // blocking side
    lock();
    thread_blocking++;
    unlock();
    sem_wait();
    lock();
    thread_blocking--;
    unlock();
    
    // signal side
    lock()
    if(thread_blocking)
        sem_post();
    unlock();
    The calls to lock() and unlock() are just locking and unlock a simple mutex. This can also be implemented with a semaphore as brewbuck described.
    bit∙hub [bit-huhb] n. A source and destination for information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Semaphores, need advice on implementation.
    By Swerve in forum C++ Programming
    Replies: 2
    Last Post: 01-13-2009, 01:54 AM
  2. semaphores
    By Dr Spud in forum C Programming
    Replies: 7
    Last Post: 09-22-2007, 12:45 PM
  3. Semaphores Problems
    By mhelal in forum Linux Programming
    Replies: 2
    Last Post: 05-06-2007, 10:36 PM
  4. semaphores
    By theLukerBoy in forum C Programming
    Replies: 0
    Last Post: 11-05-2002, 01:46 AM
  5. Semaphores
    By edk in forum C++ Programming
    Replies: 1
    Last Post: 11-25-2001, 03:55 PM