atomic operations in multithreaded c code?

Member
Posts: 45
Joined: 2006.11
Post: #1
Are there any operations in C that are sure to be atomic? I used to think the addition/assignment operations were atomic, but I've been lead to believe this isn't the case.
Quote this message in a reply
DoG
Moderator
Posts: 869
Joined: 2003.01
Post: #2
There are no inherently atomic operations in the C language, though on some implementations intrinsic atomic ops are provided by the compiler, which are used as functions.
Quote this message in a reply
Member
Posts: 161
Joined: 2005.07
Post: #3
JeroMiya Wrote:Are there any operations in C that are sure to be atomic? I used to think the addition/assignment operations were atomic, but I've been lead to believe this isn't the case.
Yep, they definitely aren't atomic.

I remember once having to do a project in C where we had two threads running at the same time on the same variable - one thread would increment a global int, and one thread would decrement it. It also kept track of how many times each one incremented and decremented the variable. Every once in a while, the value of the global int wouldn't match the number of increments and decrements we did on the value, which meant that it wasn't atomic. Something like that.
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #4
You can assume that word-sized loads and stores are atomic; just be certain that your compiler is doing what you think it is -- volatile may be necessary.

More complex operations are provided by the OS in C. For Mac OS X, look at <libkern/OSAtomic.h>; for Windows look at InterlockedCompareExchangePointer and friends; for Linux there is an equivalent compare_and_swap or something in glibc.
Quote this message in a reply
Member
Posts: 370
Joined: 2002.04
Post: #5
If you happen to be using pthreads and don't need specifically atomic operations, look into
Code:
int pthread_mutex_destroy(pthread_mutex_t *mutex)
                        Destroy a mutex.

     int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t
                        *attr)
                        Initialize a mutex with specified attributes.

     int pthread_mutex_lock(pthread_mutex_t *mutex)
                        Lock a mutex and block until it becomes available.

     int pthread_mutex_trylock(pthread_mutex_t *mutex)
                        Try to lock a mutex, but don't block if the mutex is
                        locked by another thread, including the current
                        thread.

     int pthread_mutex_unlock(pthread_mutex_t *mutex)
                        Unlock a mutex.

Did you ever wonder why we had to run for shelter when the promise of a brave new world unfurled beneath the clear blue sky?
Quote this message in a reply
Post Reply