linux - cond problem in pthread
PHP中文网
PHP中文网 2017-06-30 09:56:48
0
1
893

I encountered a problem when learning pthread. I am not sure about it. I will post the code first

#include <pthread.h>
#include <stdio.h>#include <unistd.h>

pthread_cond_t cond;
pthread_mutex_t mutex;

void *Test(void *arg) {
  pthread_mutex_lock(&mutex);
  while (1) {
    pthread_cond_wait(&cond, &mutex);
    printf("Got notified\n");
    break;
  }
  pthread_mutex_unlock(&mutex);
  return NULL;
}

int main() {
  pthread_cond_init(&cond, NULL);
  pthread_mutex_init(&mutex, NULL);
  pthread_t t;
  pthread_create(&t, NULL, Test, NULL);
  sleep(1);
  pthread_mutex_lock(&mutex);
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);
  pthread_join(t, NULL);
  printf("Exit\n");
}

If sleep(1) is commented out, it will fall into infinite waiting. If you add it (I personally think it is to ensure that another thread is already waiting to wake up before the main thread's signal), you can output two log sentences normally and exit. The reason for this phenomenon can be understood as because a thread falls into sleep because of cond_wait. Can it be woken up only by signaling cond after it sleeps? I searched online and couldn't find any article that said it specifically. Hope you can give me some advice. Or help me confirm, for a cond, assuming that thread A first calls cond_signal, and then B calls cond_wait, can B be awakened?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
女神的闺蜜爱上我

The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond). die

不能唤醒。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template