The manual
ginnOS
The reference: libc, the libraries and the kernel
Loading...
Searching...
No Matches
atomic.h
Go to the documentation of this file.
1#pragma once
2
3/**
4 * @file atomic.h
5 * @brief atomic operations on 32-bit and 64-bit words, for counters and
6 * flags that need no lock (reference counts, statistics). each
7 * operation is one locked instruction and a full barrier, as
8 * Linux's atomic_t operations that return a value.
9 */
10
11#include "common/stdint.h"
12
13/**
14 * add one to a counter.
15 * @param word the counter.
16 */
17static inline void atomic_inc(volatile uint32_t *word)
18{
19 __atomic_fetch_add(word, 1, __ATOMIC_SEQ_CST);
20}
21
22/**
23 * subtract one from a counter.
24 * @param word the counter.
25 * @return true if the counter is now 0 (the last reference went).
26 */
27static inline bool atomic_dec_and_test(volatile uint32_t *word)
28{
29 return __atomic_sub_fetch(word, 1, __ATOMIC_SEQ_CST) == 0;
30}
31
32/**
33 * put a new value in a 64-bit word.
34 * @param word the word.
35 * @param value the new value.
36 * @return the old value.
37 */
38static inline uint64_t atomic_xchg64(volatile uint64_t *word, uint64_t value)
39{
40 return __atomic_exchange_n(word, value, __ATOMIC_SEQ_CST);
41}
42
43/**
44 * change a 64-bit word only if it still has the expected value.
45 * @param word the word.
46 * @param expected the value the caller saw.
47 * @param value the new value.
48 * @return true if the word had the expected value and now has the new one.
49 */
50static inline bool atomic_cmpxchg64(volatile uint64_t *word, uint64_t expected, uint64_t value)
51{
52 return __atomic_compare_exchange_n(word, &expected, value, false, __ATOMIC_SEQ_CST,
53 __ATOMIC_SEQ_CST);
54}
55
56/**
57 * read a 64-bit word in one access (on i686 too, where a plain read is
58 * two 32-bit reads).
59 * @param word the word.
60 * @return its value.
61 */
62static inline uint64_t atomic_read64(const volatile uint64_t *word)
63{
64 return __atomic_load_n(word, __ATOMIC_SEQ_CST);
65}
unsigned int uint32_t
Definition fb.h:17
__UINT64_TYPE__ uint64_t
Definition stdint.h:17