2 +----------------------------------------------------------------------+
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
22 #include <linux/futex.h>
25 #include <folly/portability/SysTime.h>
26 #include <folly/portability/Unistd.h>
30 //////////////////////////////////////////////////////////////////////
34 inline int futex(int* uaddr
, int op
, int val
, const timespec
* timeout
,
35 int* uaddr2
, int val3
) noexcept
{
36 return syscall(SYS_futex
, uaddr
, op
, val
, timeout
, uaddr2
, val3
);
39 inline void futex_wait(std::atomic
<uint32_t>* value
, uint32_t expected
) {
40 futex(reinterpret_cast<int*>(value
), FUTEX_WAIT_PRIVATE
, expected
,
44 inline void futex_wake(std::atomic
<uint32_t>* value
, int nwake
) {
45 futex(reinterpret_cast<int*>(value
), FUTEX_WAKE_PRIVATE
, nwake
, nullptr,
51 // On non-linux OSs we do nothing for futexes. They essentially turn into spin
52 // locks. If this becomes a perf issue, it's <space intentionally left blank>
53 inline void futex_wait(std::atomic
<uint32_t>* value
, int expected
) {
56 inline void futex_wake(std::atomic
<uint32_t>* value
, int nwake
) {
61 //////////////////////////////////////////////////////////////////////
64 * A lock the size of a 4 byte int, using futex_wait when it needs to block.
66 * This structure is a standard layout class so it can be put in unions without
67 * declaring custom union constructors. Zeroing its storage is guaranteed to
68 * put it in the unlocked state, and unlocking it is guaranteed to put it back
71 * This is roughly based on http://www.akkadia.org/drepper/futex.pdf.
76 if (lock_data
.compare_exchange_strong(c
, 1, std::memory_order_acquire
)) {
81 c
= lock_data
.exchange(2, std::memory_order_acquire
);
84 futex_wait(&lock_data
, 2);
85 c
= lock_data
.exchange(2, std::memory_order_acquire
);
90 // Differs from "futexes are tricky" because std::atomic can't generate
91 // a dec instruction and test the flags.
92 if (lock_data
.exchange(0, std::memory_order_release
) != 1) {
93 futex_wake(&lock_data
, 1);
98 std::atomic
<uint32_t> lock_data
;
101 //////////////////////////////////////////////////////////////////////