Synopsis#include <glib.h> gint g_atomic_int_get (volatile gint *atomic); void g_atomic_int_set (volatile gint *atomic, gint newval); void g_atomic_int_add (volatile gint *atomic, gint val); gint g_atomic_int_exchange_and_add (volatile gint *atomic, gint val); gboolean g_atomic_int_compare_and_exchange (volatile gint *atomic, gint oldval, gint newval); gpointer g_atomic_pointer_get (volatile gpointer *atomic); void g_atomic_pointer_set (volatile gpointer *atomic, gpointer newval); gboolean g_atomic_pointer_compare_and_exchange (volatile gpointer *atomic, gpointer oldval, gpointer newval); void g_atomic_int_inc (gint *atomic); gboolean g_atomic_int_dec_and_test (gint *atomic); DescriptionThe following functions can be used to atomically access integers and pointers. They are implemented as inline assembler function on most platforms and use slower fall-backs otherwise. Using them can sometimes save you from using a performance-expensive GMutex to protect the integer or pointer.
The most important usage is reference counting. Using
Note
You must not directly read integers or pointers concurrently accessed
by multiple threads, but use the atomic accessor functions instead.
That is, always use Note
If you are using those functions for anything apart from simple
reference counting, you should really be aware of the implications of
doing that. There are literally thousands of ways to shoot yourself in
the foot. So if in doubt, use a GMutex. If you don't know, what
memory barriers are, do not use anything but Note
It is not safe to set an integer or pointer just by assigning to it,
when it is concurrently accessed by other threads with the following
functions. Use Detailsg_atomic_int_get ()gint g_atomic_int_get (volatile gint *atomic);
Reads the value of the integer pointed to by
Since 2.4 g_atomic_int_set ()void g_atomic_int_set (volatile gint *atomic, gint newval);
Sets the value of the integer pointed to by
Since 2.10 g_atomic_int_add ()void g_atomic_int_add (volatile gint *atomic, gint val);
Atomically adds
Since 2.4 g_atomic_int_exchange_and_add ()gint g_atomic_int_exchange_and_add (volatile gint *atomic, gint val);
Atomically adds
Since 2.4 g_atomic_int_compare_and_exchange ()gboolean g_atomic_int_compare_and_exchange (volatile gint *atomic, gint oldval, gint newval);
Compares
Since 2.4 g_atomic_pointer_get ()gpointer g_atomic_pointer_get (volatile gpointer *atomic);
Reads the value of the pointer pointed to by
Since 2.4 g_atomic_pointer_set ()void g_atomic_pointer_set (volatile gpointer *atomic, gpointer newval);
Sets the value of the pointer pointed to by
Since 2.10 g_atomic_pointer_compare_and_exchange ()gboolean g_atomic_pointer_compare_and_exchange (volatile gpointer *atomic, gpointer oldval, gpointer newval);
Compares
Since 2.4 g_atomic_int_inc ()void g_atomic_int_inc (gint *atomic);
Atomically increments the integer pointed to by
Since 2.4 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||