File: futex.2

package info (click to toggle)
manpages 6.15-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,184 kB
  • sloc: sh: 575; python: 222; perl: 190; makefile: 29; lisp: 22
file content (751 lines) | stat: -rw-r--r-- 24,704 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
.\" Copyright, the authors of the Linux man-pages project
.\"
.\" %%%LICENSE_START(FREELY_REDISTRIBUTABLE)
.\" may be freely modified and distributed
.\" %%%LICENSE_END
.\"
.\" FIXME Still to integrate are some points from Torvald Riegel's mail of
.\" 2015-01-23:
.\"       http://thread.gmane.org/gmane.linux.kernel/1703405/focus=7977
.\"
.\" FIXME Do we need to add some text regarding Torvald Riegel's 2015-01-24 mail
.\"       http://thread.gmane.org/gmane.linux.kernel/1703405/focus=1873242
.\"
.TH futex 2 2025-05-30 "Linux man-pages (unreleased)"
.SH NAME
futex \- fast user-space locking
.SH LIBRARY
Standard C library
.RI ( libc ,\~ \-lc )
.SH SYNOPSIS
.nf
.BR "#include <linux/futex.h>" "  /* Definition of " FUTEX_* " constants */"
.BR "#include <sys/syscall.h>" "  /* Definition of " SYS_* " constants */"
.B #include <unistd.h>
.P
.BI "long syscall(SYS_futex, uint32_t *" uaddr ", int " op ", ...);"
.fi
.SH DESCRIPTION
The
.BR futex ()
system call provides a method for waiting until a certain condition becomes
true.
It is typically used as a blocking construct in the context of
shared-memory synchronization.
When using futexes, the majority of
the synchronization operations are performed in user space.
A user-space program employs the
.BR futex ()
system call only when it is likely that the program has to block for
a longer time until the condition becomes true.
Other
.BR futex ()
operations can be used to wake any processes or threads waiting
for a particular condition.
.P
A futex is a 32-bit value\[em]referred to below as a
.IR "futex word" \[em]whose
address is supplied to the
.BR futex ()
system call.
(Futexes are 32 bits in size on all platforms, including 64-bit systems.)
All futex operations are governed by this value.
In order to share a futex between processes,
the futex is placed in a region of shared memory,
created using (for example)
.BR mmap (2)
or
.BR shmat (2).
(Thus, the futex word may have different
virtual addresses in different processes,
but these addresses all refer to the same location in physical memory.)
In a multithreaded program, it is sufficient to place the futex word
in a global variable shared by all threads.
.P
When executing a futex operation that requests to block a thread,
the kernel will block only if the futex word has the value that the
calling thread supplied (as one of the arguments of the
.BR futex ()
call) as the expected value of the futex word.
The loading of the futex word's value,
the comparison of that value with the expected value,
and the actual blocking will happen atomically and will be totally ordered
with respect to concurrent operations performed by other threads
on the same futex word.
.\" Notes from Darren Hart (Dec 2015):
.\"     Totally ordered with respect futex operations refers to semantics
.\"     of the ACQUIRE/RELEASE operations and how they impact ordering of
.\"     memory reads and writes. The kernel futex operations are protected
.\"     by spinlocks, which ensure that all operations are serialized
.\"     with respect to one another.
.\"
.\"     This is a lot to attempt to define in this document. Perhaps a
.\"     reference to linux/Documentation/memory-barriers.txt as a footnote
.\"     would be sufficient? Or perhaps for this manual, "serialized" would
.\"     be sufficient, with a footnote regarding "totally ordered" and a
.\"     pointer to the memory-barrier documentation?
Thus, the futex word is used to connect the synchronization in user space
with the implementation of blocking by the kernel.
Analogously to an atomic
compare-and-exchange operation that potentially changes shared memory,
blocking via a futex is an atomic compare-and-block operation.
.\" FIXME(Torvald Riegel):
.\" Eventually we want to have some text in NOTES to satisfy
.\" the reference in the following sentence
.\"     See NOTES for a detailed specification of
.\"     the synchronization semantics.
.P
One use of futexes is for implementing locks.
The state of the lock (i.e., acquired or not acquired)
can be represented as an atomically accessed flag in shared memory.
In the uncontended case,
a thread can access or modify the lock state with atomic instructions,
for example atomically changing it from not acquired to acquired
using an atomic compare-and-exchange instruction.
(Such instructions are performed entirely in user mode,
and the kernel maintains no information about the lock state.)
On the other hand, a thread may be unable to acquire a lock because
it is already acquired by another thread.
It then may pass the lock's flag as a futex word and the value
representing the acquired state as the expected value to a
.BR futex ()
wait operation.
This
.BR futex ()
operation will block if and only if the lock is still acquired
(i.e., the value in the futex word still matches the "acquired state").
When releasing the lock, a thread has to first reset the
lock state to not acquired and then execute a futex
operation that wakes threads blocked on the lock flag used as a futex word
(this can be further optimized to avoid unnecessary wake-ups).
See
.BR futex (7)
for more detail on how to use futexes.
.P
Besides the basic wait and wake-up futex functionality, there are further
futex operations aimed at supporting more complex use cases.
.P
Note that
no explicit initialization or destruction is necessary to use futexes;
the kernel maintains a futex
(i.e., the kernel-internal implementation artifact)
only while operations such as
.BR FUTEX_WAIT (2const)
are being performed on a particular futex word.
.\"
.SS Arguments
The
.I uaddr
argument points to the futex word.
On all platforms, futexes are four-byte
integers that must be aligned on a four-byte boundary.
The operation to perform on the futex is specified in the
.I op
argument.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SS Futex operations
The
.I op
argument consists of two parts:
a command that specifies the operation to be performed,
bitwise ORed with zero or more options that
modify the behaviour of the operation.
The options that may be included in
.I op
are as follows:
.TP
.BR FUTEX_PRIVATE_FLAG " (since Linux 2.6.22)"
.\" commit 34f01cc1f512fa783302982776895c73714ebbc2
This option bit can be employed with all futex operations.
It tells the kernel that the futex is process-private and not shared
with another process (i.e., it is being used for synchronization
only between threads of the same process).
This allows the kernel to make some additional performance optimizations.
.\" I.e., It allows the kernel choose the fast path for validating
.\" the user-space address and avoids expensive VMA lookups,
.\" taking reference counts on file backing store, and so on.
.IP
As a convenience,
.I <linux/futex.h>
defines a set of constants with the suffix
.B _PRIVATE
that are equivalents of all of the operations listed below,
.\" except the obsolete FUTEX_FD(2const), for which the "private" flag was
.\" meaningless
but with the
.B FUTEX_PRIVATE_FLAG
ORed into the constant value.
Thus, there are
.BR FUTEX_WAIT_PRIVATE ,
.BR FUTEX_WAKE_PRIVATE ,
and so on.
.TP
.BR FUTEX_CLOCK_REALTIME " (since Linux 2.6.28)"
.\" commit 1acdac104668a0834cfa267de9946fac7764d486
This option bit can be employed only with the
.BR FUTEX_WAIT_BITSET (2const),
.BR FUTEX_WAIT_REQUEUE_PI (2const),
(since Linux 4.5)
.\" commit 337f13046ff03717a9e99675284a817527440a49
.BR FUTEX_WAIT (2const),
and
(since Linux 5.14)
.\" commit bf22a6976897977b0a3f1aeba6823c959fc4fdae
.BR FUTEX_LOCK_PI2 (2const)
operations.
.IP
If this option is set, the kernel measures the
.I timeout
against the
.B CLOCK_REALTIME
clock.
.IP
If this option is not set, the kernel measures the
.I timeout
against the
.B CLOCK_MONOTONIC
clock.
.P
The operation specified in
.I op
is one of the following:
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_WAIT (2const)
.TQ
.BR FUTEX_WAKE (2const)
.TQ
.BR FUTEX_FD (2const)
.TQ
.BR FUTEX_REQUEUE (2const)
.TQ
.BR FUTEX_CMP_REQUEUE (2const)
.TQ
.BR FUTEX_WAKE_OP (2const)
.TQ
.BR FUTEX_WAIT_BITSET (2const)
.TQ
.BR FUTEX_WAKE_BITSET (2const)
.\"
.SS Priority-inheritance futexes
Linux supports priority-inheritance (PI) futexes in order to handle
priority-inversion problems that can be encountered with
normal futex locks.
Priority inversion is the problem that occurs when a high-priority
task is blocked waiting to acquire a lock held by a low-priority task,
while tasks at an intermediate priority continuously preempt
the low-priority task from the CPU.
Consequently, the low-priority task makes no progress toward
releasing the lock, and the high-priority task remains blocked.
.P
Priority inheritance is a mechanism for dealing with
the priority-inversion problem.
With this mechanism, when a high-priority task becomes blocked
by a lock held by a low-priority task,
the priority of the low-priority task is temporarily raised
to that of the high-priority task,
so that it is not preempted by any intermediate level tasks,
and can thus make progress toward releasing the lock.
To be effective, priority inheritance must be transitive,
meaning that if a high-priority task blocks on a lock
held by a lower-priority task that is itself blocked by a lock
held by another intermediate-priority task
(and so on, for chains of arbitrary length),
then both of those tasks
(or more generally, all of the tasks in a lock chain)
have their priorities raised to be the same as the high-priority task.
.P
From a user-space perspective,
what makes a futex PI-aware is a policy agreement (described below)
between user space and the kernel about the value of the futex word,
coupled with the use of the PI-futex operations described below.
(Unlike the other futex operations described above,
the PI-futex operations are designed
for the implementation of very specific IPC mechanisms.)
.\"
.\" Quoting Darren Hart:
.\"     These opcodes paired with the PI futex value policy (described below)
.\"     defines a "futex" as PI aware. These were created very specifically
.\"     in support of PI pthread_mutexes, so it makes a lot more sense to
.\"     talk about a PI aware pthread_mutex, than a PI aware futex, since
.\"     there is a lot of policy and scaffolding that has to be built up
.\"     around it to use it properly (this is what a PI pthread_mutex is).
.P
.\"       mtk: The following text is drawn from the Hart/Guniguntala paper
.\"       (listed in SEE ALSO), but I have reworded some pieces
.\"       significantly.
.\"
The PI-futex operations described below differ from the other
futex operations in that they impose policy on the use of the value of the
futex word:
.IP \[bu] 3
If the lock is not acquired, the futex word's value shall be 0.
.IP \[bu]
If the lock is acquired, the futex word's value shall
be the thread ID (TID;
see
.BR gettid (2))
of the owning thread.
.IP \[bu]
If the lock is owned and there are threads contending for the lock,
then the
.B FUTEX_WAITERS
bit shall be set in the futex word's value; in other words, this value is:
.IP
.in +4n
.EX
FUTEX_WAITERS | TID
.EE
.in
.IP
(Note that is invalid for a PI futex word to have no owner and
.B FUTEX_WAITERS
set.)
.P
With this policy in place,
a user-space application can acquire an unacquired
lock or release a lock using atomic instructions executed in user mode
(e.g., a compare-and-swap operation such as
.I cmpxchg
on the x86 architecture).
Acquiring a lock simply consists of using compare-and-swap to atomically
set the futex word's value to the caller's TID if its previous value was 0.
Releasing a lock requires using compare-and-swap to set the futex word's
value to 0 if the previous value was the expected TID.
.P
If a futex is already acquired (i.e., has a nonzero value),
waiters must employ the
.BR FUTEX_LOCK_PI (2const)
or
.BR FUTEX_LOCK_PI2 (2const)
operations to acquire the lock.
If other threads are waiting for the lock, then the
.B FUTEX_WAITERS
bit is set in the futex value;
in this case, the lock owner must employ the
.BR FUTEX_UNLOCK_PI (2const)
operation to release the lock.
.P
In the cases where callers are forced into the kernel
(i.e., required to perform a
.BR futex ()
call),
they then deal directly with a so-called RT-mutex,
a kernel locking mechanism which implements the required
priority-inheritance semantics.
After the RT-mutex is acquired, the futex value is updated accordingly,
before the calling thread returns to user space.
.P
It is important to note
.\" tglx (July 2015):
.\"     If there are multiple waiters on a pi futex then a wake pi operation
.\"     will wake the first waiter and hand over the lock to this waiter. This
.\"     includes handing over the rtmutex which represents the futex in the
.\"     kernel. The strict requirement is that the futex owner and the rtmutex
.\"     owner must be the same, except for the update period which is
.\"     serialized by the futex internal locking. That means the kernel must
.\"     update the user-space value prior to returning to user space
that the kernel will update the futex word's value prior
to returning to user space.
(This prevents the possibility of the futex word's value ending
up in an invalid state, such as having an owner but the value being 0,
or having waiters but not having the
.B FUTEX_WAITERS
bit set.)
.P
If a futex has an associated RT-mutex in the kernel
(i.e., there are blocked waiters)
and the owner of the futex/RT-mutex dies unexpectedly,
then the kernel cleans up the RT-mutex and hands it over to the next waiter.
This in turn requires that the user-space value is updated accordingly.
To indicate that this is required, the kernel sets the
.B FUTEX_OWNER_DIED
bit in the futex word along with the thread ID of the new owner.
User space can detect this situation via the presence of the
.B FUTEX_OWNER_DIED
bit and is then responsible for cleaning up the stale state left over by
the dead owner.
.\" tglx (July 2015):
.\"     The FUTEX_OWNER_DIED bit can also be set on uncontended futexes, where
.\"     the kernel has no state associated. This happens via the robust futex
.\"     mechanism. In that case the futex value will be set to
.\"     FUTEX_OWNER_DIED. The robust futex mechanism is also available for non
.\"     PI futexes.
.P
PI futexes are operated on by specifying one of the values listed below in
.IR op .
Note that the PI futex operations must be used as paired operations
and are subject to some additional requirements:
.IP \[bu] 3
.BR FUTEX_LOCK_PI (2const),
.BR FUTEX_LOCK_PI2 (2const),
and
.BR FUTEX_TRYLOCK_PI (2const)
pair with
.BR FUTEX_UNLOCK_PI (2const).
.BR FUTEX_UNLOCK_PI (2const)
must be called only on a futex owned by the calling thread,
as defined by the value policy, otherwise the error
.B EPERM
results.
.IP \[bu]
.BR FUTEX_WAIT_REQUEUE_PI (2const)
pairs with
.BR FUTEX_CMP_REQUEUE_PI (2const).
This must be performed from a non-PI futex to a distinct PI futex
(or the error
.B EINVAL
results).
Additionally,
the number of waiters to be woken must be 1
(or the error
.B EINVAL
results).
.P
The PI futex operations are as follows:
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.TP
.BR FUTEX_LOCK_PI (2const)
.TQ
.BR FUTEX_LOCK_PI2 (2const)
.TQ
.BR FUTEX_TRYLOCK_PI (2const)
.TQ
.BR FUTEX_UNLOCK_PI (2const)
.TQ
.BR FUTEX_CMP_REQUEUE_PI (2const)
.TQ
.BR FUTEX_WAIT_REQUEUE_PI (2const)
.P
The
.BR FUTEX_WAIT_REQUEUE_PI (2const)
and
.BR FUTEX_CMP_REQUEUE_PI (2const)
were added to support a fairly specific use case:
support for priority-inheritance-aware POSIX threads condition variables.
The idea is that these operations should always be paired,
in order to ensure that user space and the kernel remain in sync.
Thus, in the
.BR FUTEX_WAIT_REQUEUE_PI (2const)
operation, the user-space application pre-specifies the target
of the requeue that takes place in the
.BR FUTEX_CMP_REQUEUE_PI (2const)
operation.
.\"
.\" Darren Hart notes that a patch to allow glibc to fully support
.\" PI-aware pthreads condition variables has not yet been accepted into
.\" glibc. The story is complex, and can be found at
.\" https://sourceware.org/bugzilla/show_bug.cgi?id=11588
.\" Darren notes that in the meantime, the patch is shipped with various
.\" PREEMPT_RT-enabled Linux systems.
.\"
.\" Related to the preceding, Darren proposed that somewhere, man-pages
.\" should document the following point:
.\"
.\"     While the Linux kernel, since Linux 2.6.31, supports requeueing of
.\"     priority-inheritance (PI) aware mutexes via the
.\"     FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI futex operations,
.\"     the glibc implementation does not yet take full advantage of this.
.\"     Specifically, the condvar internal data lock remains a non-PI aware
.\"     mutex, regardless of the type of the pthread_mutex associated with
.\"     the condvar. This can lead to an unbounded priority inversion on
.\"     the internal data lock even when associating a PI aware
.\"     pthread_mutex with a condvar during a pthread_cond*_wait
.\"     operation. For this reason, it is not recommended to rely on
.\"     priority inheritance when using pthread condition variables.
.\"
.\" The problem is that the obvious location for this text is
.\" the pthread_cond*wait(3) man page. However, such a man page
.\" does not currently exist.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH RETURN VALUE
On error,
\-1 is returned,
and
.I errno
is set to indicate the error.
.P
The return value on success depends on the operation.
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH ERRORS
.TP
.B EACCES
No read access to the memory of a futex word.
.TP
.B EFAULT
.I uaddr
did not point to a valid user-space address.
.TP
.B EINVAL
.I uaddr
does not point to a valid object\[em]that is,
the address is not four-byte-aligned.
.TP
.B EINVAL
Invalid argument.
.TP
.B ENOSYS
Invalid operation specified in
.IR op .
.TP
.B ENOSYS
The
.B FUTEX_CLOCK_REALTIME
option was specified in
.IR op ,
but the accompanying operation was neither
.BR FUTEX_WAIT_BITSET (2const),
.BR FUTEX_WAIT_REQUEUE_PI (2const),
nor
.BR FUTEX_LOCK_PI2 (2const).
.\"
.\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
.\"
.SH STANDARDS
Linux.
.SH HISTORY
Linux 2.6.0.
.P
Initial futex support was merged in Linux 2.5.7 but with different
semantics from what was described above.
A four-argument system call with the semantics
described in this page was introduced in Linux 2.5.40.
A fifth argument was added in Linux 2.5.70,
and a sixth argument was added in Linux 2.6.7.
.SH EXAMPLES
The program below demonstrates use of futexes in a program where a parent
process and a child process use a pair of futexes located inside a
shared anonymous mapping to synchronize access to a shared resource:
the terminal.
The two processes each write
.I nloops
(a command-line argument that defaults to 5 if omitted)
messages to the terminal and employ a synchronization protocol
that ensures that they alternate in writing messages.
Upon running this program we see output such as the following:
.P
.in +4n
.EX
.RB $ " ./futex_demo" ;
Parent (18534) 0
Child  (18535) 0
Parent (18534) 1
Child  (18535) 1
Parent (18534) 2
Child  (18535) 2
Parent (18534) 3
Child  (18535) 3
Parent (18534) 4
Child  (18535) 4
.EE
.in
.SS Program source
\&
.\" SRC BEGIN (futex.c)
.EX
/* futex_demo.c
\&
   Usage: futex_demo [nloops]
                    (Default: 5)
\&
   Demonstrate the use of futexes in a program where parent and child
   use a pair of futexes located inside a shared anonymous mapping to
   synchronize access to a shared resource: the terminal. The two
   processes each write \[aq]num\-loops\[aq] messages to the terminal and employ
   a synchronization protocol that ensures that they alternate in
   writing messages.
*/
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
\&
static uint32_t *futex1, *futex2, *iaddr;
\&
static int
futex(uint32_t *uaddr, int op, uint32_t val,
      const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
{
    return syscall(SYS_futex, uaddr, op, val,
                   timeout, uaddr2, val3);
}
\&
/* Acquire the futex pointed to by \[aq]futexp\[aq]: wait for its value to
   become 1, and then set the value to 0. */
\&
static void
fwait(uint32_t *futexp)
{
    long            s;
    const uint32_t  one = 1;
\&
    /* atomic_compare_exchange_strong(ptr, oldval, newval)
       atomically performs the equivalent of:
\&
           if (*ptr == *oldval)
               *ptr = newval;
\&
       It returns true if the test yielded true and *ptr was updated. */
\&
    while (1) {
\&
        /* Is the futex available? */
        if (atomic_compare_exchange_strong(futexp, &one, 0))
            break;      /* Yes */
\&
        /* Futex is not available; wait. */
\&
        s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
        if (s == \-1 && errno != EAGAIN)
            err(EXIT_FAILURE, "futex\-FUTEX_WAIT");
    }
}
\&
/* Release the futex pointed to by \[aq]futexp\[aq]: if the futex currently
   has the value 0, set its value to 1 and then wake any futex waiters,
   so that if the peer is blocked in fwait(), it can proceed. */
\&
static void
fpost(uint32_t *futexp)
{
    long            s;
    const uint32_t  zero = 0;
\&
    /* atomic_compare_exchange_strong() was described
       in comments above. */
\&
    if (atomic_compare_exchange_strong(futexp, &zero, 1)) {
        s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
        if (s  == \-1)
            err(EXIT_FAILURE, "futex\-FUTEX_WAKE");
    }
}
\&
int
main(int argc, char *argv[])
{
    pid_t         childPid;
    unsigned int  nloops;
\&
    setbuf(stdout, NULL);
\&
    nloops = (argc > 1) ? atoi(argv[1]) : 5;
\&
    /* Create a shared anonymous mapping that will hold the futexes.
       Since the futexes are being shared between processes, we
       subsequently use the "shared" futex operations (i.e., not the
       ones suffixed "_PRIVATE"). */
\&
    iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,
                 MAP_ANONYMOUS | MAP_SHARED, \-1, 0);
    if (iaddr == MAP_FAILED)
        err(EXIT_FAILURE, "mmap");
\&
    futex1 = &iaddr[0];
    futex2 = &iaddr[1];
\&
    *futex1 = 0;        /* State: unavailable */
    *futex2 = 1;        /* State: available */
\&
    /* Create a child process that inherits the shared anonymous
       mapping. */
\&
    childPid = fork();
    if (childPid == \-1)
        err(EXIT_FAILURE, "fork");
\&
    if (childPid == 0) {        /* Child */
        for (unsigned int j = 0; j < nloops; j++) {
            fwait(futex1);
            printf("Child  (%jd) %u\[rs]n", (intmax_t) getpid(), j);
            fpost(futex2);
        }
\&
        exit(EXIT_SUCCESS);
    }
\&
    /* Parent falls through to here. */
\&
    for (unsigned int j = 0; j < nloops; j++) {
        fwait(futex2);
        printf("Parent (%jd) %u\[rs]n", (intmax_t) getpid(), j);
        fpost(futex1);
    }
\&
    wait(NULL);
\&
    exit(EXIT_SUCCESS);
}
.EE
.\" SRC END
.SH SEE ALSO
.ad l
.BR get_robust_list (2),
.BR restart_syscall (2),
.BR pthread_mutexattr_getprotocol (3),
.BR futex (7),
.BR sched (7)
.P
The following kernel source files:
.IP \[bu] 3
.I Documentation/pi\-futex.txt
.IP \[bu]
.I Documentation/futex\-requeue\-pi.txt
.IP \[bu]
.I Documentation/locking/rt\-mutex.txt
.IP \[bu]
.I Documentation/locking/rt\-mutex\-design.txt
.IP \[bu]
.I Documentation/robust\-futex\-ABI.txt
.P
Franke, H., Russell, R., and Kirwood, M., 2002.
.br
.UR http://kernel.org/\:doc/\:ols/\:2002/\:ols2002\-pages\-479\-495.pdf
.I Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux
.UE
(from proceedings of the Ottawa Linux Symposium 2002).
.P
Hart, D., 2009.
.UR http://lwn.net/\:Articles/\:360699/
.I A futex overview and update
.UE .
.P
Hart, D.\& and Guniguntala, D., 2009.
.UR http://lwn.net/\:images/\:conf/\:rtlws11/\:papers/\:proc/\:p10.pdf
.I Requeue-PI: Making glibc Condvars PI-Aware
.UE
(from proceedings of the 2009 Real-Time Linux Workshop).
.P
Drepper, U., 2011.
.UR http://www.akkadia.org/\:drepper/\:futex.pdf
.I Futexes Are Tricky
.UE .
.P
Futex example library,
.UR https://mirrors.kernel.org/\:pub/\:linux/\:kernel/\:people/\:rusty/
futex\-*.tar.bz2
.UE .
.\"
.\" FIXME(Torvald) We should probably refer to the glibc code here, in
.\" particular the glibc-internal futex wrapper functions that are
.\" WIP, and the generic pthread_mutex_t and perhaps condvar
.\" implementations.