Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic action - mutex

Tags:

c++

I heard that there is something known as "atomic action" which is faster then using a mutex with critical section. Does somebody know what is it, and how do I use it?

like image 343
lital maatuk Avatar asked Dec 28 '22 00:12

lital maatuk


1 Answers

An atomic operation is an operation where the CPU reads and writes memory during the same bus access, this prevents other CPUs or system devices from modifying the memory simultaneously. E.g. a "test and set" operation, which could do "read memory at location X, if it is 0 set it to 1, return an indicator telling whether the value was set" without any chance of simultaneous access.

Wikipedia's http://en.wikipedia.org/wiki/Linearizability describes atomic operations.

If you're on windows, have a look at e.g. InterlockedTestExchange or InterlockedIncrement which are wrappers for atomic operations.

EDIT: Sample usage

A spinlock could be implemented using a test-and-set atomic operation:

while (test_and_set(&x) == 1) ;

This will keep looping until the current thread is the one that sets x to 1. If all other threads treat x in the same way its effect is the same as a mutex.

like image 148
Erik Avatar answered Dec 30 '22 13:12

Erik