| 84 | } |
| 85 | |
| 86 | int bthread_cond_wait(bthread_cond_t* __restrict c, |
| 87 | bthread_mutex_t* __restrict m) { |
| 88 | bthread::CondInternal* ic = reinterpret_cast<bthread::CondInternal*>(c); |
| 89 | const int expected_seq = ic->seq->load(butil::memory_order_relaxed); |
| 90 | if (ic->m.load(butil::memory_order_relaxed) != m) { |
| 91 | // bind m to c |
| 92 | bthread_mutex_t* expected_m = NULL; |
| 93 | if (!ic->m.compare_exchange_strong( |
| 94 | expected_m, m, butil::memory_order_relaxed)) { |
| 95 | return EINVAL; |
| 96 | } |
| 97 | } |
| 98 | bthread_mutex_unlock(m); |
| 99 | int rc1 = 0; |
| 100 | if (bthread::butex_wait(ic->seq, expected_seq, NULL) < 0 && |
| 101 | errno != EWOULDBLOCK && errno != EINTR/*note*/) { |
| 102 | // EINTR should not be returned by cond_*wait according to docs on |
| 103 | // pthread, however spurious wake-up is OK, just as we do here |
| 104 | // so that users can check flags in the loop often companioning |
| 105 | // with the cond_wait ASAP. For example: |
| 106 | // mutex.lock(); |
| 107 | // while (!stop && other-predicates) { |
| 108 | // cond_wait(&mutex); |
| 109 | // } |
| 110 | // mutex.unlock(); |
| 111 | // After interruption, above code should wake up from the cond_wait |
| 112 | // soon and check the `stop' flag and other predicates. |
| 113 | rc1 = errno; |
| 114 | } |
| 115 | const int rc2 = bthread_mutex_lock_contended(m); |
| 116 | return (rc2 ? rc2 : rc1); |
| 117 | } |
| 118 | |
| 119 | int bthread_cond_timedwait(bthread_cond_t* __restrict c, |
| 120 | bthread_mutex_t* __restrict m, |