Skip to content

Commit e405fc4

Browse files
Johan Hedbergnashif
authored andcommitted
atomic: Add atomic_set_bit_to() API
Several places in the code have constructions like this: if (bool_variable) { atomic_set_bit(flags, FLAG); } else { atomic_clear_bit(flags, FLAG); } To reduce the amount of code for such situations, introduce a new atomic_set_bit_to() helper which lets you condense the above five lines to a single one: atomic_set_bit_to(flags, FLAG, bool_variable); Signed-off-by: Johan Hedberg <[email protected]>
1 parent 41f86c3 commit e405fc4

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

include/atomic.h

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,29 @@ static inline void atomic_set_bit(atomic_t *target, int bit)
411411
(void)atomic_or(ATOMIC_ELEM(target, bit), mask);
412412
}
413413

414+
/**
415+
* @brief Atomically set a bit to a given value.
416+
*
417+
* Atomically set bit number @a bit of @a target to value @a val.
418+
* The target may be a single atomic variable or an array of them.
419+
*
420+
* @param target Address of atomic variable or array.
421+
* @param bit Bit number (starting from 0).
422+
* @param val true for 1, false for 0.
423+
*
424+
* @return N/A
425+
*/
426+
static inline void atomic_set_bit_to(atomic_t *target, int bit, bool val)
427+
{
428+
atomic_val_t mask = ATOMIC_MASK(bit);
429+
430+
if (val) {
431+
(void)atomic_or(ATOMIC_ELEM(target, bit), mask);
432+
} else {
433+
(void)atomic_and(ATOMIC_ELEM(target, bit), ~mask);
434+
}
435+
}
436+
414437
/**
415438
* @}
416439
*/

tests/kernel/common/src/atomic.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,21 @@ void test_atomic(void)
142142
zassert_true(target == (orig | (1 << i)), "atomic_set_bit");
143143
}
144144

145+
/* atomic_set_bit_to(&target, i, false) */
146+
for (i = 0; i < 32; i++) {
147+
orig = 0x0F0F0F0F;
148+
target = orig;
149+
atomic_set_bit_to(&target, i, false);
150+
zassert_true(target == (orig & ~(1 << i)), "atomic_set_bit_to");
151+
}
152+
153+
/* atomic_set_bit_to(&target, i, true) */
154+
for (i = 0; i < 32; i++) {
155+
orig = 0x0F0F0F0F;
156+
target = orig;
157+
atomic_set_bit_to(&target, i, true);
158+
zassert_true(target == (orig | (1 << i)), "atomic_set_bit_to");
159+
}
145160
}
146161
/**
147162
* @}

0 commit comments

Comments
 (0)