我需要一个锁时,只有一个线程写入的共享变量? [英] Do I need a lock when only a single thread writes to a shared variable?
问题描述
我有2个线程,共享的浮动
全球。一个线程只写入变量,而对方只从中读取,我需要锁定访问这个变量?换句话说:
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?
}
}
我最关心的是,浮动的加载或存储
不是原子,这样 local_x
在 reader_thread
结束有一个假的,部分更新的价值。
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.
- 这是一个有效的关注?
- 有另一种方式来保证原子不互斥?
- 请问使用
sig_atomic_t
作为共享变量的工作,假设它有足够的位,我的目的?
- 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?
问题的语言是使用pthreads的温度。
The language in question is C using pthreads.
推荐答案
不同的架构有不同的规则,但总的来说,内存加载和存储对齐, INT
-sized对象是原子的。更小和更大可能会有问题。所以,如果的sizeof(浮点)==的sizeof(INT)
你可能是安全的,但我仍然不会在便携程序依赖于它。
Different architectures have different rules, but in general, memory loads and stores of aligned, int
-sized objects are atomic. Smaller and larger may be problematic. So if sizeof(float) == sizeof(int)
you might be safe, but I still wouldn't depend on it in a portable program.
此外,行为挥发性
没有特别明确的...规范使用它作为一种prevent优化掉访问内存 - 映射设备I / O,但没有提到它的任何其他内存访问行为。
Also, the behavior of volatile
isn't particularly well-defined... The specification uses it as a way to prevent optimizing away accesses to memory-mapped device I/O, but says nothing about its behavior on any other memory accesses.
在短,即使加载和存储的,而不是依赖于上浮法X
,我会用明确的内存屏障(尽管如何通过平台和编译器而异)原子挥发性
。如果没有加载和存储是原子的保证,你的有无的使用锁,这意味着做内存屏障。
In short, even if loads and stores are atomic on float x
, I would use explicit memory barriers (though how varies by platform and compiler) in instead of depending on volatile
. Without the guarantee of loads and stores being atomic, you would have to use locks, which do imply memory barriers.
这篇关于我需要一个锁时,只有一个线程写入的共享变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!