Your hardware may be able to atomically operate on a bool
. However, that does not make this code safe. As far as C++ is concerned, you are writing and reading the bool
in different threads without synchronisation, which is undefined.
Making the bool
static does not change that.
To access the bool
in a thread-safe way you can use a std::atomic<bool>
. Whether the atomic
uses a mutex or other locking is up to the implementation.
Though, also a std::atomic<bool>
is not sufficient to synchronize the threadReader()
and threadWriter()
in case each /*Do something */
is accessing the same shared data.
But some people told me that the fact that f is static would help.
Frankly, this sounds like cargo-cult. I can imagine that this was confused with the fact that initialization of static local variables is thread safe. From cppreference:
If multiple threads attempt to initialize the same static local
variable concurrently, the initialization occurs exactly once (similar
behavior can be obtained for arbitrary functions with std::call_once).
Note: usual implementations of this feature use variants of the
double-checked locking pattern, which reduces runtime overhead for
already-initialized local statics to a single non-atomic boolean
comparison.
Look for Meyers singleton to see an example of that. Though, this is merely about initialization. For example here:
int& foo() {
static int x = 42;
return x;
}
Two threads can call this function concurrently and x
will be initialized exactly once. This has no impact on thread-safety of x
itself. If two threads call foo
and one writes and another reads x
there is a data race. However, this is about initialization of static local variables and has nothing to do with your example. I don't know what they meant when they told you static
would "help".