In pthread, how to reliably pass signal to another thread?

前端 未结 2 669
时光取名叫无心
时光取名叫无心 2021-02-07 21:55

I\'m trying to write a simple thread pool program in pthread. However, it seems that pthread_cond_signal doesn\'t block, which creates a problem. For example, let\'

2条回答
  •  星月不相逢
    2021-02-07 22:14

    Use a synchronization variable.

    In main:

    pthread_mutex_lock(&my_cond_m);
    while (!flag) {
        pthread_cond_wait(&my_cond, &my_cond_m);
    }
    pthread_mutex_unlock(&my_cond_m);
    

    In the thread:

    pthread_mutex_lock(&my_cond_m);
    flag = 1;
    pthread_cond_broadcast(&my_cond);
    pthread_mutex_unlock(&my_cond_m);
    

    For a producer-consumer problem, this would be the consumer sleeping when the buffer is empty, and the producer sleeping when it is full. Remember to acquire the lock before accessing the global variable.

提交回复
热议问题