ygramoel
DIIDevHeads IoT Integration Server
•Created by Marvee Amasi on 4/25/2024 in #middleware-and-os
please I have a question
Even if the read is done in a single instruction, there is no guarantee that either function will read the latest value written to ga, if the write was done in another thread. The other thread might run on a different core on a multicore processor, and might be stuck in a cache of that core, so it is not available to the core running func_a or func_b. (If you do not understand what I am saying here, you might want to do some reading about modern processor architectures).
This is why in a mutithreaded program, before accessing any data that is also accessible to other threads, you must lock a mutex (the same mutex for all threads accessing the same data). "Mutex" is short for "mutual exclusion"; it is an object, often provided by an RTOS, that you can lock and unlock. The implementation of the lock and unlock functions makes sure that cached data is synced.
My conclusion is: the above code is not safe in a multithreaded environment.
16 replies