I wanted to know some API which allows me to set the value of variable, for example,
set_me = TRUE
without being pre-empted.
Actually, I have two threads viz a main thread and a timer thread, which gets invoke every second. The timer thread, every tick (say 1 ms) checks 2-3 test_me variables and based upon them change the value of 2 set_me variables. This timer thread may change the value of the set_me only in 15 - 30 ms (15-30 timeth the Timer Thread gets scheduled, it changes the set_me variable). Since the timer thread gets scheduled so often, I am reluctant to use mutex here.
So, any suggestions on how should I avoid any race conditions if possible.
I thought atomic_set could be the solution but I’ve no way to test it.
And using a few mutexes every ms it no worry at all, they are very lightweight. When there is not conflict it is only a few assembly instructions. It is only when waiting is required that the kernel is involved.
If you are a a single core machine it’s extremely unlikely to happened.
attomic_set may not do what you want because it only sets bits and does not reset them.
An operation like a = b; is atomic and doesn’t need mutex. Assuming the variable is of not of type long long which isn’t native. It’s always a good idea to set variable ‘a’ to volatile though. However ++a or a = a + 1 is not atomic because it requires reading and writing.
I’ll test with the mutex. One thing I want to ask though, will it be a good strategy to lock the mutex by the main thread just before setting the set_me variable, and unlocking the mutex soon after that? for e.g
Or should I lock the mutex just at the start of main thread function and unlock it at the end and similarly for the timer thread. So, if any one of the thread has acquired the mutex, another thread won’t be able to run, which is undesirable. Please validate my understanding.
This is fine as long as you also do the same when reading it, but as I said for an operation such as set_me=TRUE there is no need for mutexes this is an atomic operation.