Skip to content

Commit 8debeaf

Browse files
authored
contenting mutex (alibaba#992)
1 parent 480cf38 commit 8debeaf

2 files changed

Lines changed: 10 additions & 3 deletions

File tree

thread/thread.cpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1725,7 +1725,7 @@ R"(
17251725
{
17261726
assert(h->waitq == (thread_list*)this);
17271727
prelocked_thread_interrupt(h, error_number);
1728-
assert(h->waitq == nullptr);
1728+
// assert(h->waitq == nullptr);
17291729
assert(this->q.th != h);
17301730
}
17311731
return h;
@@ -1750,6 +1750,7 @@ R"(
17501750
if (unlikely(ret)) { errno = ret; return -1; }
17511751
if (try_lock() == 0) return 0;
17521752
}
1753+
again:
17531754
splock.lock();
17541755
if (try_lock() == 0) {
17551756
splock.unlock();
@@ -1764,6 +1765,10 @@ R"(
17641765

17651766
int ret = thread_usleep_defer(timeout,
17661767
(thread_list*)&q, &spinlock_unlock, &splock);
1768+
if (likely(ret < 0 && errno == -1)) {
1769+
auto o = owner.load(std::memory_order_acquire);
1770+
if (unlikely(o != CURRENT)) { assert(_contending); goto again; }
1771+
}
17671772
return waitq_translate_errno(ret);
17681773
}
17691774
int mutex::try_lock()
@@ -1777,7 +1782,7 @@ R"(
17771782
{
17781783
SCOPED_LOCK(m->splock);
17791784
ScopedLockHead h(m);
1780-
m->owner.store(h);
1785+
m->owner.store(unlikely(m->_contending) ? nullptr : (thread*)h);
17811786
if (h)
17821787
prelocked_thread_interrupt(h, -1);
17831788
}

thread/thread.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,8 @@ namespace photon
302302
class mutex : protected waitq
303303
{
304304
public:
305-
mutex(uint16_t max_retries = 100) : retries(max_retries) { }
305+
mutex(uint16_t max_retries = 100, bool contending = false)
306+
: retries(max_retries), _contending(contending) { }
306307
int lock(Timeout timeout = {});
307308
int try_lock();
308309
void unlock();
@@ -315,6 +316,7 @@ namespace photon
315316
std::atomic<thread*> owner{nullptr};
316317
uint16_t retries;
317318
spinlock splock;
319+
bool _contending;
318320
};
319321

320322
class seq_mutex : protected mutex {

0 commit comments

Comments
 (0)