How to implement add_fetch for atomic?

Rus atomic only has fetch_add like APIs, which returns the previous value.
It lacks add_fetch APIs, which returns the result of add

Gcc provides both __atomic_fetch_add and __atomic_add_fetch for C/C++

Why Rust does not provide add_fetch?
and how to achieve the same effect when I need add_fetch?

As noted in this GitHub Issue, you can implement add_fetch as follows:

fn add_fetch(a: &AtomicUsize, b: usize, order: Ordering) -> usize {
    a.fetch_add(b, order) + b
}
2 Likes

Thanks. To be precise,
wrapping_add should be used, since overflowing is not checked in fetch_and,
nor should add_fetch

use core::sync::atomic::{Ordering, AtomicUsize};
fn add_fetch(a: &AtomicUsize, b: usize, order: Ordering) -> usize {
    a.fetch_add(b, order).wrapping_add(b)
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.