我有2个线程和一个共享float全局.一个线程只写入变量,而另一个只读取它,我是否需要锁定对此变量的访问?换一种说法:
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?
}
}
Run Code Online (Sandbox Code Playgroud)
我主要关注的是,一个的加载或存储float不是原子,使得local_x在reader_thread结束有一个假的,部分更新后的值.
sig_atomic_t作为共享变量的工作,假设它有足够的位用于我的目的?有问题的语言是C使用pthreads.