For the below C++ code
volatile bool keepRunning = true;
void run() {
while (keepRunning) {
doSomeWork();
}
}
void stop() {
keepRunning = false;
}
suppose one thread executes stop() and multiple threads are executing run()
I believe this kind of construct (one writer, no synchronization primitives) is quite prevalent in embedded systems. Is this guaranteed to work, assuming there’s no multiple processors/cores?
Thanks
Yes, because on a unicore machine there is only one CPU and one CPU-cache.
Another reason: To the CPU, it looks like there is only one thread running. The CPU is obliged to present the application a view of memory which is equivalent to single-threaded execution because the CPU can’t even tell that there are multiple threads.