2 .\" and Copyright (C) 2015, Thomas Gleixner <tglx@linutronix.de>
3 .\" and Copyright (C) 2015, Michael Kerrisk <mtk.manpages@gmail.com>
5 .\" %%%LICENSE_START(FREELY_REDISTRIBUTABLE)
6 .\" may be freely modified and distributed
9 .\" Niki A. Rahimi (LTC Security Development, narahimi@us.ibm.com)
10 .\" added ERRORS section.
12 .\" Modified 2004-06-17 mtk
13 .\" Modified 2004-10-07 aeb, added FUTEX_REQUEUE, FUTEX_CMP_REQUEUE
15 .\" FIXME Still to integrate are some points from Torvald Riegel's mail of
17 .\" http://thread.gmane.org/gmane.linux.kernel/1703405/focus=7977
19 .\" FIXME Do we need to add some text regarding Torvald Riegel's 2015-01-24 mail
20 .\" http://thread.gmane.org/gmane.linux.kernel/1703405/focus=1873242
22 .TH FUTEX 2 2021-03-22 "Linux" "Linux Programmer's Manual"
24 futex \- fast user-space locking
28 .BR "#include <linux/futex.h>" " /* Definition of " FUTEX_* " constants */"
29 .BR "#include <sys/syscall.h>" " /* Definition of " SYS_* " constants */"
30 .B #include <unistd.h>
32 .BI "long syscall(SYS_futex, uint32_t *" uaddr ", int " futex_op \
34 .BI " const struct timespec *" timeout , \
35 " \fR /* or: \fBuint32_t \fIval2\fP */"
36 .BI " uint32_t *" uaddr2 ", uint32_t " val3 );
40 glibc provides no wrapper for
42 necessitating the use of
47 system call provides a method for waiting until a certain condition becomes
49 It is typically used as a blocking construct in the context of
50 shared-memory synchronization.
51 When using futexes, the majority of
52 the synchronization operations are performed in user space.
53 A user-space program employs the
55 system call only when it is likely that the program has to block for
56 a longer time until the condition becomes true.
59 operations can be used to wake any processes or threads waiting
60 for a particular condition.
62 A futex is a 32-bit value\(emreferred to below as a
63 .IR "futex word" \(emwhose
64 address is supplied to the
67 (Futexes are 32 bits in size on all platforms, including 64-bit systems.)
68 All futex operations are governed by this value.
69 In order to share a futex between processes,
70 the futex is placed in a region of shared memory,
71 created using (for example)
75 (Thus, the futex word may have different
76 virtual addresses in different processes,
77 but these addresses all refer to the same location in physical memory.)
78 In a multithreaded program, it is sufficient to place the futex word
79 in a global variable shared by all threads.
81 When executing a futex operation that requests to block a thread,
82 the kernel will block only if the futex word has the value that the
83 calling thread supplied (as one of the arguments of the
85 call) as the expected value of the futex word.
86 The loading of the futex word's value,
87 the comparison of that value with the expected value,
88 and the actual blocking will happen atomically and will be totally ordered
89 with respect to concurrent operations performed by other threads
90 on the same futex word.
91 .\" Notes from Darren Hart (Dec 2015):
92 .\" Totally ordered with respect futex operations refers to semantics
93 .\" of the ACQUIRE/RELEASE operations and how they impact ordering of
94 .\" memory reads and writes. The kernel futex operations are protected
95 .\" by spinlocks, which ensure that all operations are serialized
96 .\" with respect to one another.
98 .\" This is a lot to attempt to define in this document. Perhaps a
99 .\" reference to linux/Documentation/memory-barriers.txt as a footnote
100 .\" would be sufficient? Or perhaps for this manual, "serialized" would
101 .\" be sufficient, with a footnote regarding "totally ordered" and a
102 .\" pointer to the memory-barrier documentation?
103 Thus, the futex word is used to connect the synchronization in user space
104 with the implementation of blocking by the kernel.
105 Analogously to an atomic
106 compare-and-exchange operation that potentially changes shared memory,
107 blocking via a futex is an atomic compare-and-block operation.
108 .\" FIXME(Torvald Riegel):
109 .\" Eventually we want to have some text in NOTES to satisfy
110 .\" the reference in the following sentence
111 .\" See NOTES for a detailed specification of
112 .\" the synchronization semantics.
114 One use of futexes is for implementing locks.
115 The state of the lock (i.e., acquired or not acquired)
116 can be represented as an atomically accessed flag in shared memory.
117 In the uncontended case,
118 a thread can access or modify the lock state with atomic instructions,
119 for example atomically changing it from not acquired to acquired
120 using an atomic compare-and-exchange instruction.
121 (Such instructions are performed entirely in user mode,
122 and the kernel maintains no information about the lock state.)
123 On the other hand, a thread may be unable to acquire a lock because
124 it is already acquired by another thread.
125 It then may pass the lock's flag as a futex word and the value
126 representing the acquired state as the expected value to a
131 operation will block if and only if the lock is still acquired
132 (i.e., the value in the futex word still matches the "acquired state").
133 When releasing the lock, a thread has to first reset the
134 lock state to not acquired and then execute a futex
135 operation that wakes threads blocked on the lock flag used as a futex word
136 (this can be further optimized to avoid unnecessary wake-ups).
139 for more detail on how to use futexes.
141 Besides the basic wait and wake-up futex functionality, there are further
142 futex operations aimed at supporting more complex use cases.
145 no explicit initialization or destruction is necessary to use futexes;
146 the kernel maintains a futex
147 (i.e., the kernel-internal implementation artifact)
148 only while operations such as
150 described below, are being performed on a particular futex word.
155 argument points to the futex word.
156 On all platforms, futexes are four-byte
157 integers that must be aligned on a four-byte boundary.
158 The operation to perform on the futex is specified in the
162 is a value whose meaning and purpose depends on
165 The remaining arguments
170 are required only for certain of the futex operations described below.
171 Where one of these arguments is not required, it is ignored.
173 For several blocking operations, the
175 argument is a pointer to a
177 structure that specifies a timeout for the operation.
178 However, notwithstanding the prototype shown above, for some operations,
179 the least significant four bytes of this argument are instead
180 used as an integer whose meaning is determined by the operation.
181 For these operations, the kernel casts the
187 and in the remainder of this page, this argument is referred to as
189 when interpreted in this fashion.
191 Where it is required, the
193 argument is a pointer to a second futex word that is employed
196 The interpretation of the final integer argument,
198 depends on the operation.
200 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
205 argument consists of two parts:
206 a command that specifies the operation to be performed,
207 bitwise ORed with zero or more options that
208 modify the behaviour of the operation.
209 The options that may be included in
213 .BR FUTEX_PRIVATE_FLAG " (since Linux 2.6.22)"
214 .\" commit 34f01cc1f512fa783302982776895c73714ebbc2
215 This option bit can be employed with all futex operations.
216 It tells the kernel that the futex is process-private and not shared
217 with another process (i.e., it is being used for synchronization
218 only between threads of the same process).
219 This allows the kernel to make some additional performance optimizations.
220 .\" I.e., It allows the kernel choose the fast path for validating
221 .\" the user-space address and avoids expensive VMA lookups,
222 .\" taking reference counts on file backing store, and so on.
226 defines a set of constants with the suffix
228 that are equivalents of all of the operations listed below,
229 .\" except the obsolete FUTEX_FD, for which the "private" flag was
232 .BR FUTEX_PRIVATE_FLAG
233 ORed into the constant value.
235 .BR FUTEX_WAIT_PRIVATE ,
236 .BR FUTEX_WAKE_PRIVATE ,
239 .BR FUTEX_CLOCK_REALTIME " (since Linux 2.6.28)"
240 .\" commit 1acdac104668a0834cfa267de9946fac7764d486
241 This option bit can be employed only with the
242 .BR FUTEX_WAIT_BITSET ,
243 .BR FUTEX_WAIT_REQUEUE_PI ,
246 .\" commit 337f13046ff03717a9e99675284a817527440a49
250 If this option is set, the kernel measures the
256 If this option is not set, the kernel measures the
262 The operation specified in
264 is one of the following:
266 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
269 .BR FUTEX_WAIT " (since Linux 2.6.0)"
270 .\" Strictly speaking, since some time in 2.5.x
271 This operation tests that the value at the
272 futex word pointed to by the address
274 still contains the expected value
276 and if so, then sleeps waiting for a
278 operation on the futex word.
279 The load of the value of the futex word is an atomic memory
280 access (i.e., using atomic machine instructions of the respective
282 This load, the comparison with the expected value, and
283 starting to sleep are performed atomically
284 .\" FIXME: Torvald, I think we may need to add some explanation of
285 .\" "totally ordered" here.
287 with respect to other futex operations on the same futex word.
288 If the thread starts to sleep,
289 it is considered a waiter on this futex word.
290 If the futex value does not match
292 then the call fails immediately with the error
295 The purpose of the comparison with the expected value is to prevent lost
297 If another thread changed the value of the futex word after the
298 calling thread decided to block based on the prior value,
299 and if the other thread executed a
301 operation (or similar wake-up) after the value change and before this
303 operation, then the calling thread will observe the
304 value change and will not start to sleep.
308 is not NULL, the structure it points to specifies a
309 timeout for the wait.
310 (This interval will be rounded up to the system clock granularity,
311 and is guaranteed not to expire early.)
312 The timeout is by default measured according to the
314 clock, but, since Linux 4.5, the
316 clock can be selected by specifying
317 .BR FUTEX_CLOCK_REALTIME
322 is NULL, the call blocks indefinitely.
331 This differs from other futex operations, where
333 is interpreted as an absolute value.
334 To obtain the equivalent of
336 with an absolute timeout, employ
337 .BR FUTEX_WAIT_BITSET
341 .BR FUTEX_BITSET_MATCH_ANY .
348 .\" FIXME . (Torvald) I think we should remove this. Or maybe adapt to a
349 .\" different example.
353 .\" this call is executed if decrementing the count gave a negative value
354 .\" (indicating contention),
355 .\" and will sleep until another process or thread releases
356 .\" the futex and executes the
360 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
363 .BR FUTEX_WAKE " (since Linux 2.6.0)"
364 .\" Strictly speaking, since Linux 2.5.x
365 This operation wakes at most
367 of the waiters that are waiting (e.g., inside
369 on the futex word at the address
373 is specified as either 1 (wake up a single waiter) or
375 (wake up all waiters).
376 No guarantee is provided about which waiters are awoken
377 (e.g., a waiter with a higher scheduling priority is not guaranteed
378 to be awoken in preference to a waiter with a lower priority).
386 .\" FIXME . (Torvald) I think we should remove this. Or maybe adapt to
387 .\" a different example.
391 .\" this is executed if incrementing the count showed that
392 .\" there were waiters,
393 .\" once the futex value has been set to 1
394 .\" (indicating that it is available).
396 .\" How does "incrementing the count show that there were waiters"?
398 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
401 .BR FUTEX_FD " (from Linux 2.6.0 up to and including Linux 2.6.25)"
402 .\" Strictly speaking, from Linux 2.5.x to 2.6.25
403 This operation creates a file descriptor that is associated with
406 The caller must close the returned file descriptor after use.
407 When another process or thread performs a
409 on the futex word, the file descriptor indicates as being readable with
415 The file descriptor can be used to obtain asynchronous notifications: if
417 is nonzero, then, when another process or thread executes a
419 the caller will receive the signal number that was passed in
429 Because it was inherently racy,
432 .\" commit 82af7aca56c67061420d618cc5a30f0fd4106b80
433 from Linux 2.6.26 onward.
435 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
438 .BR FUTEX_REQUEUE " (since Linux 2.6.0)"
439 This operation performs the same task as
440 .BR FUTEX_CMP_REQUEUE
441 (see below), except that no check is made using the value in
447 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
450 .BR FUTEX_CMP_REQUEUE " (since Linux 2.6.7)"
451 This operation first checks whether the location
453 still contains the value
455 If not, the operation fails with the error
457 Otherwise, the operation wakes up a maximum of
459 waiters that are waiting on the futex at
461 If there are more than
463 waiters, then the remaining waiters are removed
464 from the wait queue of the source futex at
466 and added to the wait queue of the target futex at
470 argument specifies an upper limit on the number of waiters
471 that are requeued to the futex at
474 .\" FIXME(Torvald) Is the following correct? Or is just the decision
475 .\" which threads to wake or requeue part of the atomic operation?
478 is an atomic memory access (i.e., using atomic machine instructions of
479 the respective architecture).
480 This load, the comparison with
482 and the requeueing of any waiters are performed atomically and totally
483 ordered with respect to other operations on the same futex word.
484 .\" Notes from a f2f conversation with Thomas Gleixner (Aug 2015): ###
485 .\" The operation is serialized with respect to operations on both
486 .\" source and target futex. No other waiter can enqueue itself
487 .\" for waiting and no other waiter can dequeue itself because of
488 .\" a timeout or signal.
490 Typical values to specify for
495 is not useful, because it would make the
496 .BR FUTEX_CMP_REQUEUE
497 operation equivalent to
499 The limit value specified via
501 is typically either 1 or
503 (Specifying the argument as 0 is not useful, because it would make the
504 .BR FUTEX_CMP_REQUEUE
505 operation equivalent to
510 operation was added as a replacement for the earlier
512 The difference is that the check of the value at
514 can be used to ensure that requeueing happens only under certain
515 conditions, which allows race conditions to be avoided in certain use cases.
516 .\" But, as Rich Felker points out, there remain valid use cases for
517 .\" FUTEX_REQUEUE, for example, when the calling thread is requeuing
518 .\" the target(s) to a lock that the calling thread owns
519 .\" From: Rich Felker <dalias@libc.org>
520 .\" Date: Wed, 29 Oct 2014 22:43:17 -0400
521 .\" To: Darren Hart <dvhart@infradead.org>
522 .\" CC: libc-alpha@sourceware.org, ...
523 .\" Subject: Re: Add futex wrapper to glibc?
528 .BR FUTEX_CMP_REQUEUE
529 can be used to avoid "thundering herd" wake-ups that could occur when using
531 in cases where all of the waiters that are woken need to acquire
533 Consider the following scenario,
534 where multiple waiter threads are waiting on B,
535 a wait queue implemented using a futex:
540 while (!check_value(V)) {
549 If a waker thread used
551 then all waiters waiting on B would be woken up,
552 and they would all try to acquire lock A.
553 However, waking all of the threads in this manner would be pointless because
554 all except one of the threads would immediately block on lock A again.
555 By contrast, a requeue operation wakes just one waiter and moves
556 the other waiters to lock A,
557 and when the woken waiter unlocks A then the next waiter can proceed.
559 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
562 .BR FUTEX_WAKE_OP " (since Linux 2.6.14)"
563 .\" commit 4732efbeb997189d9f9b04708dc26bf8613ed721
564 .\" Author: Jakub Jelinek <jakub@redhat.com>
565 .\" Date: Tue Sep 6 15:16:25 2005 -0700
566 .\" FIXME. (Torvald) The glibc condvar implementation is currently being
567 .\" revised (e.g., to not use an internal lock anymore).
568 .\" It is probably more future-proof to remove this paragraph.
569 .\" [Torvald, do you have an update here?]
570 This operation was added to support some user-space use cases
571 where more than one futex must be handled at the same time.
572 The most notable example is the implementation of
573 .BR pthread_cond_signal (3),
574 which requires operations on two futexes,
575 the one used to implement the mutex and the one used in the implementation
576 of the wait queue associated with the condition variable.
578 allows such cases to be implemented without leading to
579 high rates of contention and context switching.
583 operation is equivalent to executing the following code atomically
584 and totally ordered with respect to other futex operations on
585 any of the two supplied futex words:
589 uint32_t oldval = *(uint32_t *) uaddr2;
590 *(uint32_t *) uaddr2 = oldval \fIop\fP \fIoparg\fP;
591 futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
592 if (oldval \fIcmp\fP \fIcmparg\fP)
593 futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);
602 saves the original value of the futex word at
604 and performs an operation to modify the value of the futex at
606 this is an atomic read-modify-write memory access (i.e., using atomic
607 machine instructions of the respective architecture)
609 wakes up a maximum of
611 waiters on the futex for the futex word at
615 dependent on the results of a test of the original value of the
618 wakes up a maximum of
620 waiters on the futex for the futex word at
624 The operation and comparison that are to be performed are encoded
625 in the bits of the argument
627 Pictorially, the encoding is:
631 +---+---+-----------+-----------+
632 |op |cmp| oparg | cmparg |
633 +---+---+-----------+-----------+
634 4 4 12 12 <== # of bits
638 Expressed in code, the encoding is:
642 #define FUTEX_OP(op, oparg, cmp, cmparg) \e
643 (((op & 0xf) << 28) | \e
644 ((cmp & 0xf) << 24) | \e
645 ((oparg & 0xfff) << 12) | \e
654 are each one of the codes listed below.
659 components are literal numeric values, except as noted below.
663 component has one of the following values:
667 FUTEX_OP_SET 0 /* uaddr2 = oparg; */
668 FUTEX_OP_ADD 1 /* uaddr2 += oparg; */
669 FUTEX_OP_OR 2 /* uaddr2 |= oparg; */
670 FUTEX_OP_ANDN 3 /* uaddr2 &= \(tioparg; */
671 FUTEX_OP_XOR 4 /* uaddr2 \(ha= oparg; */
675 In addition, bitwise ORing the following value into
679 to be used as the operand:
683 FUTEX_OP_ARG_SHIFT 8 /* Use (1 << oparg) as operand */
689 field is one of the following:
693 FUTEX_OP_CMP_EQ 0 /* if (oldval == cmparg) wake */
694 FUTEX_OP_CMP_NE 1 /* if (oldval != cmparg) wake */
695 FUTEX_OP_CMP_LT 2 /* if (oldval < cmparg) wake */
696 FUTEX_OP_CMP_LE 3 /* if (oldval <= cmparg) wake */
697 FUTEX_OP_CMP_GT 4 /* if (oldval > cmparg) wake */
698 FUTEX_OP_CMP_GE 5 /* if (oldval >= cmparg) wake */
704 is the sum of the number of waiters woken on the futex
706 plus the number of waiters woken on the futex
709 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
712 .BR FUTEX_WAIT_BITSET " (since Linux 2.6.25)"
713 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
714 This operation is like
718 is used to provide a 32-bit bit mask to the kernel.
719 This bit mask, in which at least one bit must be set,
720 is stored in the kernel-internal state of the waiter.
721 See the description of
722 .BR FUTEX_WAKE_BITSET
727 is not NULL, the structure it points to specifies
728 an absolute timeout for the wait operation.
731 is NULL, the operation can block indefinitely.
737 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
740 .BR FUTEX_WAKE_BITSET " (since Linux 2.6.25)"
741 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
742 This operation is the same as
746 argument is used to provide a 32-bit bit mask to the kernel.
747 This bit mask, in which at least one bit must be set,
748 is used to select which waiters should be woken up.
749 The selection is done by a bitwise AND of the "wake" bit mask
752 and the bit mask which is stored in the kernel-internal
753 state of the waiter (the "wait" bit mask that is set using
754 .BR FUTEX_WAIT_BITSET ).
755 All of the waiters for which the result of the AND is nonzero are woken up;
756 the remaining waiters are left sleeping.
759 .BR FUTEX_WAIT_BITSET
761 .BR FUTEX_WAKE_BITSET
762 is to allow selective wake-ups among multiple waiters that are blocked
764 However, note that, depending on the use case,
765 employing this bit-mask multiplexing feature on a
766 futex can be less efficient than simply using multiple futexes,
767 because employing bit-mask multiplexing requires the kernel
768 to check all waiters on a futex,
769 including those that are not interested in being woken up
770 (i.e., they do not have the relevant bit set in their "wait" bit mask).
771 .\" According to http://locklessinc.com/articles/futex_cheat_sheet/:
773 .\" "The original reason for the addition of these extensions
774 .\" was to improve the performance of pthread read-write locks
775 .\" in glibc. However, the pthreads library no longer uses the
776 .\" same locking algorithm, and these extensions are not used
777 .\" without the bitset parameter being all ones.
779 .\" The page goes on to note that the FUTEX_WAIT_BITSET operation
780 .\" is nevertheless used (with a bit mask of all ones) in order to
781 .\" obtain the absolute timeout functionality that is useful
782 .\" for efficiently implementing Pthreads APIs (which use absolute
783 .\" timeouts); FUTEX_WAIT provides only relative timeouts.
786 .BR FUTEX_BITSET_MATCH_ANY ,
787 which corresponds to all 32 bits set in the bit mask, can be used as the
790 .BR FUTEX_WAIT_BITSET
792 .BR FUTEX_WAKE_BITSET .
793 Other than differences in the handling of the
797 operation is equivalent to
798 .BR FUTEX_WAIT_BITSET
802 .BR FUTEX_BITSET_MATCH_ANY ;
803 that is, allow a wake-up by any waker.
806 operation is equivalent to
807 .BR FUTEX_WAKE_BITSET
811 .BR FUTEX_BITSET_MATCH_ANY ;
812 that is, wake up any waiter(s).
818 arguments are ignored.
820 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
822 .SS Priority-inheritance futexes
823 Linux supports priority-inheritance (PI) futexes in order to handle
824 priority-inversion problems that can be encountered with
826 Priority inversion is the problem that occurs when a high-priority
827 task is blocked waiting to acquire a lock held by a low-priority task,
828 while tasks at an intermediate priority continuously preempt
829 the low-priority task from the CPU.
830 Consequently, the low-priority task makes no progress toward
831 releasing the lock, and the high-priority task remains blocked.
833 Priority inheritance is a mechanism for dealing with
834 the priority-inversion problem.
835 With this mechanism, when a high-priority task becomes blocked
836 by a lock held by a low-priority task,
837 the priority of the low-priority task is temporarily raised
838 to that of the high-priority task,
839 so that it is not preempted by any intermediate level tasks,
840 and can thus make progress toward releasing the lock.
841 To be effective, priority inheritance must be transitive,
842 meaning that if a high-priority task blocks on a lock
843 held by a lower-priority task that is itself blocked by a lock
844 held by another intermediate-priority task
845 (and so on, for chains of arbitrary length),
846 then both of those tasks
847 (or more generally, all of the tasks in a lock chain)
848 have their priorities raised to be the same as the high-priority task.
850 From a user-space perspective,
851 what makes a futex PI-aware is a policy agreement (described below)
852 between user space and the kernel about the value of the futex word,
853 coupled with the use of the PI-futex operations described below.
854 (Unlike the other futex operations described above,
855 the PI-futex operations are designed
856 for the implementation of very specific IPC mechanisms.)
858 .\" Quoting Darren Hart:
859 .\" These opcodes paired with the PI futex value policy (described below)
860 .\" defines a "futex" as PI aware. These were created very specifically
861 .\" in support of PI pthread_mutexes, so it makes a lot more sense to
862 .\" talk about a PI aware pthread_mutex, than a PI aware futex, since
863 .\" there is a lot of policy and scaffolding that has to be built up
864 .\" around it to use it properly (this is what a PI pthread_mutex is).
866 .\" mtk: The following text is drawn from the Hart/Guniguntala paper
867 .\" (listed in SEE ALSO), but I have reworded some pieces
870 The PI-futex operations described below differ from the other
871 futex operations in that they impose policy on the use of the value of the
874 If the lock is not acquired, the futex word's value shall be 0.
876 If the lock is acquired, the futex word's value shall
877 be the thread ID (TID;
880 of the owning thread.
882 If the lock is owned and there are threads contending for the lock,
885 bit shall be set in the futex word's value; in other words, this value is:
889 (Note that is invalid for a PI futex word to have no owner and
893 With this policy in place,
894 a user-space application can acquire an unacquired
895 lock or release a lock using atomic instructions executed in user mode
896 (e.g., a compare-and-swap operation such as
898 on the x86 architecture).
899 Acquiring a lock simply consists of using compare-and-swap to atomically
900 set the futex word's value to the caller's TID if its previous value was 0.
901 Releasing a lock requires using compare-and-swap to set the futex word's
902 value to 0 if the previous value was the expected TID.
904 If a futex is already acquired (i.e., has a nonzero value),
905 waiters must employ the
907 operation to acquire the lock.
908 If other threads are waiting for the lock, then the
910 bit is set in the futex value;
911 in this case, the lock owner must employ the
913 operation to release the lock.
915 In the cases where callers are forced into the kernel
916 (i.e., required to perform a
919 they then deal directly with a so-called RT-mutex,
920 a kernel locking mechanism which implements the required
921 priority-inheritance semantics.
922 After the RT-mutex is acquired, the futex value is updated accordingly,
923 before the calling thread returns to user space.
925 It is important to note
926 .\" tglx (July 2015):
927 .\" If there are multiple waiters on a pi futex then a wake pi operation
928 .\" will wake the first waiter and hand over the lock to this waiter. This
929 .\" includes handing over the rtmutex which represents the futex in the
930 .\" kernel. The strict requirement is that the futex owner and the rtmutex
931 .\" owner must be the same, except for the update period which is
932 .\" serialized by the futex internal locking. That means the kernel must
933 .\" update the user-space value prior to returning to user space
934 that the kernel will update the futex word's value prior
935 to returning to user space.
936 (This prevents the possibility of the futex word's value ending
937 up in an invalid state, such as having an owner but the value being 0,
938 or having waiters but not having the
942 If a futex has an associated RT-mutex in the kernel
943 (i.e., there are blocked waiters)
944 and the owner of the futex/RT-mutex dies unexpectedly,
945 then the kernel cleans up the RT-mutex and hands it over to the next waiter.
946 This in turn requires that the user-space value is updated accordingly.
947 To indicate that this is required, the kernel sets the
949 bit in the futex word along with the thread ID of the new owner.
950 User space can detect this situation via the presence of the
952 bit and is then responsible for cleaning up the stale state left over by
954 .\" tglx (July 2015):
955 .\" The FUTEX_OWNER_DIED bit can also be set on uncontended futexes, where
956 .\" the kernel has no state associated. This happens via the robust futex
957 .\" mechanism. In that case the futex value will be set to
958 .\" FUTEX_OWNER_DIED. The robust futex mechanism is also available for non
961 PI futexes are operated on by specifying one of the values listed below in
963 Note that the PI futex operations must be used as paired operations
964 and are subject to some additional requirements:
970 .BR FUTEX_UNLOCK_PI .
972 must be called only on a futex owned by the calling thread,
973 as defined by the value policy, otherwise the error
977 .B FUTEX_WAIT_REQUEUE_PI
979 .BR FUTEX_CMP_REQUEUE_PI .
980 This must be performed from a non-PI futex to a distinct PI futex
986 (the number of waiters to be woken) must be 1
991 The PI futex operations are as follows:
993 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
996 .BR FUTEX_LOCK_PI " (since Linux 2.6.18)"
997 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
998 This operation is used after an attempt to acquire
999 the lock via an atomic user-mode instruction failed
1000 because the futex word has a nonzero value\(emspecifically,
1001 because it contained the (PID-namespace-specific) TID of the lock owner.
1003 The operation checks the value of the futex word at the address
1005 If the value is 0, then the kernel tries to atomically set
1006 the futex value to the caller's TID.
1007 If the futex word's value is nonzero,
1008 the kernel atomically sets the
1010 bit, which signals the futex owner that it cannot unlock the futex in
1011 user space atomically by setting the futex value to 0.
1012 .\" tglx (July 2015):
1013 .\" The operation here is similar to the FUTEX_WAIT logic. When the user
1014 .\" space atomic acquire does not succeed because the futex value was non
1015 .\" zero, then the waiter goes into the kernel, takes the kernel internal
1016 .\" lock and retries the acquisition under the lock. If the acquisition
1017 .\" does not succeed either, then it sets the FUTEX_WAITERS bit, to signal
1018 .\" the lock owner that it needs to go into the kernel. Here is the pseudo
1021 .\" lock(kernel_lock);
1025 .\" * Owner might have unlocked in user space before we
1026 .\" * were able to set the waiter bit.
1028 .\" if (atomic_acquire(futex) == SUCCESS) {
1029 .\" unlock(kernel_lock());
1034 .\" * Owner might have unlocked after the above atomic_acquire()
1037 .\" if (atomic_set_waiters_bit(futex) != SUCCESS)
1041 .\" unlock(kernel_lock);
1044 After that, the kernel:
1047 Tries to find the thread which is associated with the owner TID.
1049 Creates or reuses kernel state on behalf of the owner.
1050 (If this is the first waiter, there is no kernel state for this
1051 futex, so kernel state is created by locking the RT-mutex
1052 and the futex owner is made the owner of the RT-mutex.
1053 If there are existing waiters, then the existing state is reused.)
1055 Attaches the waiter to the futex
1056 (i.e., the waiter is enqueued on the RT-mutex waiter list).
1059 If more than one waiter exists,
1060 the enqueueing of the waiter is in descending priority order.
1061 (For information on priority ordering, see the discussion of the
1062 .BR SCHED_DEADLINE ,
1066 scheduling policies in
1068 The owner inherits either the waiter's CPU bandwidth
1069 (if the waiter is scheduled under the
1071 policy) or the waiter's priority (if the waiter is scheduled under the
1077 .\" mtk: If the realm is restricted purely to SCHED_OTHER (SCHED_NORMAL)
1078 .\" processes, does the nice value come into play also?
1080 .\" tglx: No. SCHED_OTHER/NORMAL tasks are handled in FIFO order
1081 This inheritance follows the lock chain in the case of nested locking
1082 .\" (i.e., task 1 blocks on lock A, held by task 2,
1083 .\" while task 2 blocks on lock B, held by task 3)
1084 and performs deadlock detection.
1088 argument provides a timeout for the lock attempt.
1091 is not NULL, the structure it points to specifies
1092 an absolute timeout, measured against the
1095 .\" 2016-07-07 response from Thomas Gleixner on LKML:
1096 .\" From: Thomas Gleixner <tglx@linutronix.de>
1097 .\" Date: 6 July 2016 at 20:57
1098 .\" Subject: Re: futex: Allow FUTEX_CLOCK_REALTIME with FUTEX_WAIT op
1100 .\" On Thu, 23 Jun 2016, Michael Kerrisk (man-pages) wrote:
1101 .\" > On 06/23/2016 08:28 PM, Darren Hart wrote:
1102 .\" > > And as a follow-on, what is the reason for FUTEX_LOCK_PI only using
1103 .\" > > CLOCK_REALTIME? It seems reasonable to me that a user may want to wait a
1104 .\" > > specific amount of time, regardless of wall time.
1106 .\" > Yes, that's another weird inconsistency.
1108 .\" The reason is that phtread_mutex_timedlock() uses absolute timeouts based on
1109 .\" CLOCK_REALTIME. glibc folks asked to make that the default behaviour back
1110 .\" then when we added LOCK_PI.
1113 is NULL, the operation will block indefinitely.
1120 arguments are ignored.
1122 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1125 .BR FUTEX_TRYLOCK_PI " (since Linux 2.6.18)"
1126 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1127 This operation tries to acquire the lock at
1129 It is invoked when a user-space atomic acquire did not
1130 succeed because the futex word was not 0.
1132 Because the kernel has access to more state information than user space,
1133 acquisition of the lock might succeed if performed by the
1134 kernel in cases where the futex word
1135 (i.e., the state information accessible to use-space) contains stale state
1138 .BR FUTEX_OWNER_DIED ).
1139 This can happen when the owner of the futex died.
1140 User space cannot handle this condition in a race-free manner,
1141 but the kernel can fix this up and acquire the futex.
1142 .\" Paraphrasing a f2f conversation with Thomas Gleixner about the
1143 .\" above point (Aug 2015): ###
1144 .\" There is a rare possibility of a race condition involving an
1145 .\" uncontended futex with no owner, but with waiters. The
1146 .\" kernel-user-space contract is that if a futex is nonzero, you must
1147 .\" go into kernel. The futex was owned by a task, and that task dies
1148 .\" but there are no waiters, so the futex value is non zero.
1149 .\" Therefore, the next locker has to go into the kernel,
1150 .\" so that the kernel has a chance to clean up. (CMXCH on zero
1151 .\" in user space would fail, so kernel has to clean up.)
1152 .\" Darren Hart (Oct 2015):
1153 .\" The trylock in the kernel has more state, so it can independently
1154 .\" verify the flags that user space must trust implicitly.
1162 arguments are ignored.
1164 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1167 .BR FUTEX_UNLOCK_PI " (since Linux 2.6.18)"
1168 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1169 This operation wakes the top priority waiter that is waiting in
1171 on the futex address provided by the
1175 This is called when the user-space value at
1177 cannot be changed atomically from a TID (of the owner) to 0.
1185 arguments are ignored.
1187 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1190 .BR FUTEX_CMP_REQUEUE_PI " (since Linux 2.6.31)"
1191 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1192 This operation is a PI-aware variant of
1193 .BR FUTEX_CMP_REQUEUE .
1194 It requeues waiters that are blocked via
1195 .B FUTEX_WAIT_REQUEUE_PI
1198 from a non-PI source futex
1200 to a PI target futex
1204 .BR FUTEX_CMP_REQUEUE ,
1205 this operation wakes up a maximum of
1207 waiters that are waiting on the futex at
1210 .BR FUTEX_CMP_REQUEUE_PI ,
1213 (since the main point is to avoid a thundering herd).
1214 The remaining waiters are removed from the wait queue of the source futex at
1216 and added to the wait queue of the target futex at
1221 .\" val2 is the cap on the number of requeued waiters.
1222 .\" In the glibc pthread_cond_broadcast() implementation, this argument
1223 .\" is specified as INT_MAX, and for pthread_cond_signal() it is 0.
1226 arguments serve the same purposes as for
1227 .BR FUTEX_CMP_REQUEUE .
1229 .\" The page at http://locklessinc.com/articles/futex_cheat_sheet/
1230 .\" notes that "priority-inheritance Futex to priority-inheritance
1231 .\" Futex requeues are currently unsupported". However, probably
1232 .\" the page does not need to say nothing about this, since
1233 .\" Thomas Gleixner commented (July 2015): "they never will be
1234 .\" supported because they make no sense at all"
1236 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1239 .BR FUTEX_WAIT_REQUEUE_PI " (since Linux 2.6.31)"
1240 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1242 Wait on a non-PI futex at
1244 and potentially be requeued (via a
1245 .BR FUTEX_CMP_REQUEUE_PI
1246 operation in another task) onto a PI futex at
1248 The wait operation on
1253 The waiter can be removed from the wait on
1255 without requeueing on
1259 operation in another task.
1261 .BR FUTEX_WAIT_REQUEUE_PI
1262 operation fails with the error
1267 is not NULL, the structure it points to specifies
1268 an absolute timeout for the wait operation.
1271 is NULL, the operation can block indefinitely.
1275 argument is ignored.
1278 .BR FUTEX_WAIT_REQUEUE_PI
1280 .BR FUTEX_CMP_REQUEUE_PI
1281 were added to support a fairly specific use case:
1282 support for priority-inheritance-aware POSIX threads condition variables.
1283 The idea is that these operations should always be paired,
1284 in order to ensure that user space and the kernel remain in sync.
1286 .BR FUTEX_WAIT_REQUEUE_PI
1287 operation, the user-space application pre-specifies the target
1288 of the requeue that takes place in the
1289 .BR FUTEX_CMP_REQUEUE_PI
1292 .\" Darren Hart notes that a patch to allow glibc to fully support
1293 .\" PI-aware pthreads condition variables has not yet been accepted into
1294 .\" glibc. The story is complex, and can be found at
1295 .\" https://sourceware.org/bugzilla/show_bug.cgi?id=11588
1296 .\" Darren notes that in the meantime, the patch is shipped with various
1297 .\" PREEMPT_RT-enabled Linux systems.
1299 .\" Related to the preceding, Darren proposed that somewhere, man-pages
1300 .\" should document the following point:
1302 .\" While the Linux kernel, since 2.6.31, supports requeueing of
1303 .\" priority-inheritance (PI) aware mutexes via the
1304 .\" FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI futex operations,
1305 .\" the glibc implementation does not yet take full advantage of this.
1306 .\" Specifically, the condvar internal data lock remains a non-PI aware
1307 .\" mutex, regardless of the type of the pthread_mutex associated with
1308 .\" the condvar. This can lead to an unbounded priority inversion on
1309 .\" the internal data lock even when associating a PI aware
1310 .\" pthread_mutex with a condvar during a pthread_cond*_wait
1311 .\" operation. For this reason, it is not recommended to rely on
1312 .\" priority inheritance when using pthread condition variables.
1314 .\" The problem is that the obvious location for this text is
1315 .\" the pthread_cond*wait(3) man page. However, such a man page
1316 .\" does not currently exist.
1318 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1321 In the event of an error (and assuming that
1325 all operations return \-1 and set
1327 to indicate the error.
1329 The return value on success depends on the operation,
1330 as described in the following list:
1333 Returns 0 if the caller was woken up.
1334 Note that a wake-up can also be caused by common futex usage patterns
1335 in unrelated code that happened to have previously used the futex word's
1336 memory location (e.g., typical futex-based implementations of
1337 Pthreads mutexes can cause this under some conditions).
1338 Therefore, callers should always conservatively assume that a return
1339 value of 0 can mean a spurious wake-up, and use the futex word's value
1340 (i.e., the user-space synchronization scheme)
1341 to decide whether to continue to block or not.
1344 Returns the number of waiters that were woken up.
1347 Returns the new file descriptor associated with the futex.
1350 Returns the number of waiters that were woken up.
1352 .B FUTEX_CMP_REQUEUE
1353 Returns the total number of waiters that were woken up or
1354 requeued to the futex for the futex word at
1356 If this value is greater than
1358 then the difference is the number of waiters requeued to the futex for the
1363 Returns the total number of waiters that were woken up.
1364 This is the sum of the woken waiters on the two futexes for
1370 .B FUTEX_WAIT_BITSET
1371 Returns 0 if the caller was woken up.
1374 for how to interpret this correctly in practice.
1376 .B FUTEX_WAKE_BITSET
1377 Returns the number of waiters that were woken up.
1380 Returns 0 if the futex was successfully locked.
1383 Returns 0 if the futex was successfully locked.
1386 Returns 0 if the futex was successfully unlocked.
1388 .B FUTEX_CMP_REQUEUE_PI
1389 Returns the total number of waiters that were woken up or
1390 requeued to the futex for the futex word at
1392 If this value is greater than
1394 then difference is the number of waiters requeued to the futex for
1398 .B FUTEX_WAIT_REQUEUE_PI
1399 Returns 0 if the caller was successfully requeued to the futex for
1403 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1408 No read access to the memory of a futex word.
1412 .BR FUTEX_WAIT_BITSET ,
1413 .BR FUTEX_WAIT_REQUEUE_PI )
1414 The value pointed to by
1416 was not equal to the expected value
1418 at the time of the call.
1421 on Linux, the symbolic names
1425 (both of which appear in different parts of the kernel futex code)
1426 have the same value.
1429 .RB ( FUTEX_CMP_REQUEUE ,
1430 .BR FUTEX_CMP_REQUEUE_PI )
1431 The value pointed to by
1433 is not equal to the expected value
1437 .RB ( FUTEX_LOCK_PI ,
1438 .BR FUTEX_TRYLOCK_PI ,
1439 .BR FUTEX_CMP_REQUEUE_PI )
1440 The futex owner thread ID of
1443 .BR FUTEX_CMP_REQUEUE_PI :
1446 but has not yet handled the internal state cleanup.
1450 .RB ( FUTEX_LOCK_PI ,
1451 .BR FUTEX_TRYLOCK_PI ,
1452 .BR FUTEX_CMP_REQUEUE_PI )
1455 is already locked by the caller.
1458 .\" FIXME . I see that kernel/locking/rtmutex.c uses EDEADLK in some
1459 .\" places, and EDEADLOCK in others. On almost all architectures
1460 .\" these constants are synonymous. Is there a reason that both
1463 .\" tglx (July 2015): "No. We should probably fix that."
1465 .RB ( FUTEX_CMP_REQUEUE_PI )
1466 While requeueing a waiter to the PI futex for the futex word at
1468 the kernel detected a deadlock.
1471 A required pointer argument (i.e.,
1476 did not point to a valid user-space address.
1482 .B FUTEX_WAIT_BITSET
1483 operation was interrupted by a signal (see
1485 In kernels before Linux 2.6.22, this error could also be returned for
1486 a spurious wakeup; since Linux 2.6.22, this no longer happens.
1491 is one of those that employs a timeout, but the supplied
1493 argument was invalid
1495 was less than zero, or
1497 was not less than 1,000,000,000).
1500 The operation specified in
1502 employs one or both of the pointers
1506 but one of these does not point to a valid object\(emthat is,
1507 the address is not four-byte-aligned.
1510 .RB ( FUTEX_WAIT_BITSET ,
1511 .BR FUTEX_WAKE_BITSET )
1512 The bit mask supplied in
1517 .RB ( FUTEX_CMP_REQUEUE_PI )
1521 (i.e., an attempt was made to requeue to the same futex).
1525 The signal number supplied in
1532 .BR FUTEX_WAKE_BITSET ,
1534 .BR FUTEX_CMP_REQUEUE )
1535 The kernel detected an inconsistency between the user-space state at
1537 and the kernel state\(emthat is, it detected a waiter which waits in
1543 .RB ( FUTEX_LOCK_PI ,
1544 .BR FUTEX_TRYLOCK_PI ,
1545 .BR FUTEX_UNLOCK_PI )
1546 The kernel detected an inconsistency between the user-space state at
1548 and the kernel state.
1549 This indicates either state corruption
1550 or that the kernel found a waiter on
1552 which is waiting via
1555 .BR FUTEX_WAIT_BITSET .
1558 .RB ( FUTEX_CMP_REQUEUE_PI )
1559 The kernel detected an inconsistency between the user-space state at
1561 and the kernel state;
1562 .\" From a conversation with Thomas Gleixner (Aug 2015): ###
1563 .\" The kernel sees: I have non PI state for a futex you tried to
1565 that is, the kernel detected a waiter which waits via
1568 .BR FUTEX_WAIT_BITSET
1573 .RB ( FUTEX_CMP_REQUEUE_PI )
1574 The kernel detected an inconsistency between the user-space state at
1576 and the kernel state;
1577 that is, the kernel detected a waiter which waits via
1580 .BR FUTEX_WAIT_BITSET
1585 .RB ( FUTEX_CMP_REQUEUE_PI )
1586 The kernel detected an inconsistency between the user-space state at
1588 and the kernel state;
1589 that is, the kernel detected a waiter which waits on
1594 .BR FUTEX_WAIT_REQUEUE_PI ).
1597 .RB ( FUTEX_CMP_REQUEUE_PI )
1598 .\" This deals with the case:
1599 .\" wait_requeue_pi(A, B);
1600 .\" requeue_pi(A, C);
1601 An attempt was made to requeue a waiter to a futex other than that
1602 specified by the matching
1603 .B FUTEX_WAIT_REQUEUE_PI
1604 call for that waiter.
1607 .RB ( FUTEX_CMP_REQUEUE_PI )
1617 The system-wide limit on the total number of open files has been reached.
1620 .RB ( FUTEX_LOCK_PI ,
1621 .BR FUTEX_TRYLOCK_PI ,
1622 .BR FUTEX_CMP_REQUEUE_PI )
1623 The kernel could not allocate memory to hold state information.
1626 Invalid operation specified in
1631 .BR FUTEX_CLOCK_REALTIME
1632 option was specified in
1634 but the accompanying operation was neither
1636 .BR FUTEX_WAIT_BITSET ,
1638 .BR FUTEX_WAIT_REQUEUE_PI .
1641 .RB ( FUTEX_LOCK_PI ,
1642 .BR FUTEX_TRYLOCK_PI ,
1643 .BR FUTEX_UNLOCK_PI ,
1644 .BR FUTEX_CMP_REQUEUE_PI ,
1645 .BR FUTEX_WAIT_REQUEUE_PI )
1646 A run-time check determined that the operation is not available.
1647 The PI-futex operations are not implemented on all architectures and
1648 are not supported on some CPU variants.
1651 .RB ( FUTEX_LOCK_PI ,
1652 .BR FUTEX_TRYLOCK_PI ,
1653 .BR FUTEX_CMP_REQUEUE_PI )
1654 The caller is not allowed to attach itself to the futex at
1657 .BR FUTEX_CMP_REQUEUE_PI :
1660 (This may be caused by a state corruption in user space.)
1663 .RB ( FUTEX_UNLOCK_PI )
1664 The caller does not own the lock represented by the futex word.
1667 .RB ( FUTEX_LOCK_PI ,
1668 .BR FUTEX_TRYLOCK_PI ,
1669 .BR FUTEX_CMP_REQUEUE_PI )
1670 The thread ID in the futex word at
1675 .RB ( FUTEX_CMP_REQUEUE_PI )
1676 The thread ID in the futex word at
1683 employed the timeout specified in
1685 and the timeout expired before the operation completed.
1687 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1690 Futexes were first made available in a stable kernel release
1693 Initial futex support was merged in Linux 2.5.7 but with different
1694 semantics from what was described above.
1695 A four-argument system call with the semantics
1696 described in this page was introduced in Linux 2.5.40.
1697 A fifth argument was added in Linux 2.5.70,
1698 and a sixth argument was added in Linux 2.6.7.
1700 This system call is Linux-specific.
1702 Several higher-level programming abstractions are implemented via futexes,
1703 including POSIX semaphores and
1704 various POSIX threads synchronization mechanisms
1705 (mutexes, condition variables, read-write locks, and barriers).
1706 .\" TODO FIXME(Torvald) Above, we cite this section and claim it contains
1707 .\" details on the synchronization semantics; add the C11 equivalents
1708 .\" here (or whatever we find consensus for).
1710 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1713 The program below demonstrates use of futexes in a program where a parent
1714 process and a child process use a pair of futexes located inside a
1715 shared anonymous mapping to synchronize access to a shared resource:
1717 The two processes each write
1719 (a command-line argument that defaults to 5 if omitted)
1720 messages to the terminal and employ a synchronization protocol
1721 that ensures that they alternate in writing messages.
1722 Upon running this program we see output such as the following:
1726 $ \fB./futex_demo\fP
1744 Usage: futex_demo [nloops]
1747 Demonstrate the use of futexes in a program where parent and child
1748 use a pair of futexes located inside a shared anonymous mapping to
1749 synchronize access to a shared resource: the terminal. The two
1750 processes each write \(aqnum\-loops\(aq messages to the terminal and employ
1751 a synchronization protocol that ensures that they alternate in
1757 #include <stdatomic.h>
1761 #include <sys/wait.h>
1762 #include <sys/mman.h>
1763 #include <sys/syscall.h>
1764 #include <linux/futex.h>
1765 #include <sys/time.h>
1767 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
1770 static uint32_t *futex1, *futex2, *iaddr;
1773 futex(uint32_t *uaddr, int futex_op, uint32_t val,
1774 const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
1776 return syscall(SYS_futex, uaddr, futex_op, val,
1777 timeout, uaddr2, val3);
1780 /* Acquire the futex pointed to by \(aqfutexp\(aq: wait for its value to
1781 become 1, and then set the value to 0. */
1784 fwait(uint32_t *futexp)
1788 /* atomic_compare_exchange_strong(ptr, oldval, newval)
1789 atomically performs the equivalent of:
1791 if (*ptr == *oldval)
1794 It returns true if the test yielded true and *ptr was updated. */
1798 /* Is the futex available? */
1799 const uint32_t one = 1;
1800 if (atomic_compare_exchange_strong(futexp, &one, 0))
1803 /* Futex is not available; wait. */
1805 s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
1806 if (s == \-1 && errno != EAGAIN)
1807 errExit("futex\-FUTEX_WAIT");
1811 /* Release the futex pointed to by \(aqfutexp\(aq: if the futex currently
1812 has the value 0, set its value to 1 and the wake any futex waiters,
1813 so that if the peer is blocked in fwait(), it can proceed. */
1816 fpost(uint32_t *futexp)
1820 /* atomic_compare_exchange_strong() was described
1821 in comments above. */
1823 const uint32_t zero = 0;
1824 if (atomic_compare_exchange_strong(futexp, &zero, 1)) {
1825 s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
1827 errExit("futex\-FUTEX_WAKE");
1832 main(int argc, char *argv[])
1837 setbuf(stdout, NULL);
1839 nloops = (argc > 1) ? atoi(argv[1]) : 5;
1841 /* Create a shared anonymous mapping that will hold the futexes.
1842 Since the futexes are being shared between processes, we
1843 subsequently use the "shared" futex operations (i.e., not the
1844 ones suffixed "_PRIVATE"). */
1846 iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,
1847 MAP_ANONYMOUS | MAP_SHARED, \-1, 0);
1848 if (iaddr == MAP_FAILED)
1854 *futex1 = 0; /* State: unavailable */
1855 *futex2 = 1; /* State: available */
1857 /* Create a child process that inherits the shared anonymous
1861 if (childPid == \-1)
1864 if (childPid == 0) { /* Child */
1865 for (int j = 0; j < nloops; j++) {
1867 printf("Child (%jd) %d\en", (intmax_t) getpid(), j);
1874 /* Parent falls through to here. */
1876 for (int j = 0; j < nloops; j++) {
1878 printf("Parent (%jd) %d\en", (intmax_t) getpid(), j);
1889 .BR get_robust_list (2),
1890 .BR restart_syscall (2),
1891 .BR pthread_mutexattr_getprotocol (3),
1895 The following kernel source files:
1897 .I Documentation/pi\-futex.txt
1899 .I Documentation/futex\-requeue\-pi.txt
1901 .I Documentation/locking/rt\-mutex.txt
1903 .I Documentation/locking/rt\-mutex\-design.txt
1905 .I Documentation/robust\-futex\-ABI.txt
1907 Franke, H., Russell, R., and Kirwood, M., 2002.
1908 \fIFuss, Futexes and Furwocks: Fast Userlevel Locking in Linux\fP
1909 (from proceedings of the Ottawa Linux Symposium 2002),
1911 .UR http://kernel.org\:/doc\:/ols\:/2002\:/ols2002\-pages\-479\-495.pdf
1914 Hart, D., 2009. \fIA futex overview and update\fP,
1915 .UR http://lwn.net/Articles/360699/
1918 Hart, D.\& and Guniguntala, D., 2009.
1919 \fIRequeue-PI: Making Glibc Condvars PI-Aware\fP
1920 (from proceedings of the 2009 Real-Time Linux Workshop),
1921 .UR http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf
1924 Drepper, U., 2011. \fIFutexes Are Tricky\fP,
1925 .UR http://www.akkadia.org/drepper/futex.pdf
1928 Futex example library, futex-*.tar.bz2 at
1930 .UR ftp://ftp.kernel.org\:/pub\:/linux\:/kernel\:/people\:/rusty/
1933 .\" FIXME(Torvald) We should probably refer to the glibc code here, in
1934 .\" particular the glibc-internal futex wrapper functions that are
1935 .\" WIP, and the generic pthread_mutex_t and perhaps condvar
1936 .\" implementations.