eesweng
eesweng

Reputation: 21

Does pthread_cond_wait() acquire the mutex immediately after being signalled?

I have a thread, A, whose function runs in a loop, does something and wakes another thread, B, up. Then it releases the mutex and goes on with next iteration. Thread B waits until being signalled, then does something. My question is, Is it guaranteed that B will acquire the mutex after being signalled or can thread A re-acquire the mutex before B, in the next iteration of the loop?

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t signal = PTHREAD_COND_INITIALIZER;

int condition=0;

//function for thread A
void func_A(void *arg){
    while(1) {
      pthread_mutex_lock(&lock);
      do_something();
      condition=1;
      pthread_cond_signal(&signal);
      pthread_mutex_unlock(&lock);
    }
}

//function for thread B
void func_B(void *arg) {
    while(1) {
      pthread_mutex_lock(&lock);
      while(condition = 0)
        pthread_cond_wait(&signal, &lock);
      do_something_else();
      condition=0;
      pthread_mutex_unlock(&lock);
    }
}

Is there a way to make sure B acquires the mutex after it is signalled?

Upvotes: 0

Views: 282

Answers (2)

eesweng
eesweng

Reputation: 21

So, I overcame this problem by using a semaphore which is initialized to 1. Thread A performs a sem_wait() operation on the semaphore, before locking the mutex lock. Thread B performs a sem_post() operation on the semaphore, before relasing the mutex lock.

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t signal = PTHREAD_COND_INITIALIZER;

sem_t my_sem; //properly initialized with value set to 1

int condition=0;

//function for thread A
void func_A(void *arg){
    while(1) {
      sem_wait(&my_sem);  //notice the change
      pthread_mutex_lock(&lock);
      do_something();
      condition=1;
      pthread_cond_signal(&signal);
      pthread_mutex_unlock(&lock);
    }
}

//function for thread B
void func_B(void *arg) {
    while(1) {
      pthread_mutex_lock(&lock);
      while(condition = 0)
        pthread_cond_wait(&signal, &lock);
      do_something_else();
      condition=0;
      sem_post(&my_sem);  //notice the change
      pthread_mutex_unlock(&lock);
    }
}

Upvotes: 0

Tsyvarev
Tsyvarev

Reputation: 65928

Is there a way to make sure B acquires the mutex after it is signalled?

No, there is no such way - B will compete with other threads for owning the mutex, as usual.

Also, how do expect B to automatically acquires mutex on being signaled, when A owns the mutex at the time it signals?

Upvotes: 1

Related Questions