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 +----------------------------------------------------------------------+
16 #ifndef incl_HPHP_SMALLLOCKS_H_
17 #define incl_HPHP_SMALLLOCKS_H_
23 #include <linux/futex.h>
26 #include <folly/portability/SysTime.h>
27 #include <folly/portability/Unistd.h>
31 //////////////////////////////////////////////////////////////////////
35 inline int futex(int* uaddr
, int op
, int val
, const timespec
* timeout
,
36 int* uaddr2
, int val3
) noexcept
{
37 return syscall(SYS_futex
, uaddr
, op
, val
, timeout
, uaddr2
, val3
);
40 inline void futex_wait(std::atomic
<int>* value
, int expected
) {
41 futex(reinterpret_cast<int*>(value
), FUTEX_WAIT_PRIVATE
, expected
,
45 inline void futex_wake(std::atomic
<int>* value
, int nwake
) {
46 futex(reinterpret_cast<int*>(value
), FUTEX_WAKE_PRIVATE
, nwake
, nullptr,
52 // On non-linux OSs we do nothing for futexes. They essentially turn into spin
53 // locks. If this becomes a perf issue, it's <space intentionally left blank>
54 inline void futex_wait(std::atomic
<int>* value
, int expected
) {
57 inline void futex_wake(std::atomic
<int>* value
, int nwake
) {
62 //////////////////////////////////////////////////////////////////////
65 * A lock the size of a 4 byte int, using futex_wait when it needs to block.
67 * This structure is a standard layout class so it can be put in unions without
68 * declaring custom union constructors. Zeroing its storage is guaranteed to
69 * put it in the unlocked state, and unlocking it is guaranteed to put it back
72 * This is roughly based on http://www.akkadia.org/drepper/futex.pdf.
77 if (lock_data
.compare_exchange_strong(c
, 1, std::memory_order_acquire
)) {
82 c
= lock_data
.exchange(2, std::memory_order_acquire
);
85 futex_wait(&lock_data
, 2);
86 c
= lock_data
.exchange(2, std::memory_order_acquire
);
91 // Differs from "futexes are tricky" because std::atomic can't generate
92 // a dec instruction and test the flags.
93 if (lock_data
.exchange(0, std::memory_order_release
) != 1) {
94 futex_wake(&lock_data
, 1);
99 std::atomic
<int> lock_data
;
102 //////////////////////////////////////////////////////////////////////