tags:

views:

183

answers:

1

I previously inquired about synchronizing two threads without using pthread_join and I was able to resolve it using pthread_cond_wait and pthread_cond_signal. I've written a small struct to bundle this functionality into a single place:

struct ConditionWait
{
    int     i_ConditionPredicate;
    pthread_mutex_t  lock_Var;
    pthread_cond_t  cond_Var;
    int     i_ValidResult;

    ConditionWait()
    {
     pthread_mutex_init(&lock_Var, NULL);
     pthread_cond_init(&cond_Var, NULL);
     i_ValidResult = 1;
     i_ConditionPredicate = 0;
    }

    void Signal()
    {
     pthread_mutex_lock(&lock_Var);
     i_ConditionPredicate = i_ValidResult;
     pthread_cond_signal(&cond_Var);
     pthread_mutex_unlock(&lock_Var);
    }

    void Wait()
    {
     pthread_mutex_lock(&lock_Var);

     while(i_ConditionPredicate != i_ValidResult)
     {
      pthread_cond_wait(&cond_Var, &lock_Var);
     }
     pthread_mutex_unlock(&lock_Var);
    }
};

Assuming that I call Wait() and Signal() from two different threads, would this be thread safe. Would taking the same lock in two functions of the same object cause deadlocks or race conditions?

Edit: I'm using this now in my program and it works fine. I'm not too sure whether it's just luck

+3  A: 

This will only work once, after you wake up the thread waiting, the next attempts to wait will all succeed and never block since you never "reset" the condition predicate. If this is what you want (or it doesn't matter in your situation) then yes, this is safe and is how condition variables are typically used.

PS: You should also use pthread_mutex_destroy() and pthread_cond_destroy() in the destructor of this thing.

Greg Rogers