GCC offers a good set of built-in functions for atomic operations. And on MacOS or iOS, even Apple offers a good set of atomic features . However, all these functions perform an operation, for example. addition / subtraction, logical operation (AND / OR / XOR) or comparison and set / comparison and exchange. What I'm looking for is a way to atomize / read an int value, for example:
int a; a = someVariable;
It's all. a will be read by another thread, and it is only important that a has its old meaning or new value. Unfortunately, the C standard does not guarantee that assigning or reading a value is an atomic operation. I remember that once I read somewhere that writing or reading a value of a variable of type int guaranteed to be atomic in GCC (regardless of the size of int), but I searched everywhere on the GCC main page and I cannot find this statement ( it may have been deleted).
I cannot use sig_atomic_t because sig_atomic_t does not have a guaranteed size and can have a different size than int .
Since only one thread will ever “write” the value to a , while both threads will “read” the current value of a , I do not need to perform the operations themselves in atomic mode, for example
someVariable = atomicRead(a); atomicWrite(a, someVariable); someVariable = atomicRead(a);
If both threads write to a , then all operations should be atomic, but, thus, this can only lead to cancellation of processor time; and in our project we are extremely low for CPU resources. Until now, we use the mutex around read / write operations a , and although the mutex is held for such a tiny period of time, this is already causing problems (one of the threads is a real-time thread and blocking on the mutex forces it to reject restrictions in real time, which is very bad).
Of course, I could use __sync_fetch_and_add to read the variable (and just add “0” to it so as not to change its value), and to write use __sync_val_compare_and_swap to write it (since I know its old value, so go through this to make sure that the value is always exchanged), but doesn’t it add extra overhead?