I have 2 threads and a shared float
global. One thread only writes to the variable while the other only reads from it, do I need to lock access to this variable? In other words:
volatile float x;
void reader_thread() {
while (1) {
// Grab mutex here?
float local_x = x;
// Release mutex?
do_stuff_with_value(local_x);
}
}
void writer_thread() {
while (1) {
float local_x = get_new_value_from_somewhere();
// Grab mutex here?
x = local_x;
// Release mutex?
}
}
My main concern is that a load or store of a float
not being atomic, such that local_x
in reader_thread
ends up having a bogus, partially updated value.
- Is this a valid concern?
- Is there another way to guarantee atomicity without a mutex?
- Would using
sig_atomic_t
as the shared variable work, assuming it has enough bits for my purposes?
The language in question is C using pthreads.