【perf】reduce pthread_cond_signal via wait counter

pthread_cond_signal is not needed in case that no thread is blocked on the cond var.

Take a inter-thread shared queue as an example,  which maintains a counter couting blocked threads

 1 void pop(void **data) {
 2     pthread_mutex_lock(&mtx);
 3     while (queue_size == 0) {
 4         count++;
 5         pthread_cond_wait(&cv, &mtx);
 6         count--;
 7     }
 8     // ... pop the front item into data
 9     pthread_mutex_lock(&mtx);
10 }
11 
12 void push(void *data) {
13     pthread_mutex_lock(&mtx);
14     // ... push data into queue
15     if (count > 0) {
16         pthread_cond_signal(&cv);
17     }
18     pthread_mutex_lock(&mtx);
19 }

猜你喜欢

转载自www.cnblogs.com/albumcover/p/9339059.html