pthread_cond_wait()是否在发出信号后立即获取互斥体?

时间:2019-03-30 14:56:32

标签: c multithreading pthreads

我有一个线程A,它的功能循环运行,执行某些操作并唤醒另一个线程B。然后释放互斥量并继续下一次迭代。线程B等待直到收到信号通知,然后执行某些操作。我的问题是,是否可以保证B在收到信号后将获取互斥锁,或者线程A可以在循环的下一次迭代中在B之前重新获取互斥锁?

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);
    }
}

有没有一种方法可以确保B在收到信号后获得互斥体?

2 个答案:

答案 0 :(得分:1)

  

有没有一种方法可以确保B在收到信号后获得互斥体?

没有,没有这样的方法-bool a = p.Get<bool>();将像往常一样与其他线程竞争拥有互斥量。

此外,当#include <stdio.h> int main() { int a[5] = { 5, 1, 15, 20, 25 }; i = ++a[1]; // a[1] is incremented, becomes 2, i gets this value 2 j = a[1]++; // j gets a[1] which is 2, then a[1] is incremented and becomes 3 m = a[i++]; // m gets a[2] which is 15, i is incremented and becomes 3 printf("%d %d %d", i, j, m); // prints 3 2 15 return 0; } 发出信号时拥有互斥锁时,怎么期望B在收到信号后自动获取互斥锁?

答案 1 :(得分:0)

因此,我通过使用初始化为1的信号量解决了这个问题。线程A在锁定互斥锁sem_wait()之前对信号量执行了lock操作。在重新释放互斥锁sem_post()之前,线程B对信号量执行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);
    }
}