user1202136
user1202136

Reputation: 11567

How to implement atomic_min?

I need to implement an atomic_min function, that is equivalent to:

static void atomic_min(u64 *ptr, u64 value)                                        
{
    enter critical section
    *ptr = min(*ptr, value);
    exit critical section                                                                               
}

This could be implement it using cmpxchg:

static void atomic_min(u64 *ptr, u64 value)                                        
{                                                                                
    u64 old, new;                                                            
    do {                                                                     
        old = *ptr;                                                        
        new = min(old, value);                                           
    } while (cmpxchg(ptr, old, new) != old);
}

which looks pretty inefficient to me. Is there a better way to implement atomic_min?

Upvotes: 0

Views: 622

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 66337

Atomic arithmetic instructions, provided by architectures, are mostly limited with addition/substruction and bitwise operations. (At least, Linux kernel provides only those operations for arch-independent code).

Because min cannot be expressed via single addition, substruction or bitwise operations, for implement "atomic_min" there is no other choice than using of cmpxchg.

Upvotes: 3

Related Questions