[英]Should I mutex lock a single variable?
If a single 32-bit variable is shared between multiple threads, should I put a mutex lock around the variable?如果一个 32 位变量在多个线程之间共享,我应该在变量周围放置一个互斥锁吗? For example, suppose 1 thread writes to a 32-bit counter and a 2nd thread reads it.
例如,假设 1 个线程写入 32 位计数器,而第 2 个线程读取它。 Is there any chance the 2nd thread could read a corrupted value?
第二个线程是否有可能读取损坏的值?
I'm working on a 32-bit ARM embedded system.我正在开发一个 32 位 ARM 嵌入式系统。 The compiler always seems to align 32-bit variables so they can be read or written with a single instruction.
编译器似乎总是对齐 32 位变量,以便可以用一条指令读取或写入它们。 If the 32-bit variable was not aligned, then the read or write would be broken down into multiple instructions and the 2nd thread could read a corrupted value.
如果 32 位变量未对齐,则读取或写入将分解为多条指令,第二个线程可能读取损坏的值。
Does the answer to this question change if I move to a multiple-core system in the future and the variable is shared between cores?如果我将来迁移到多核系统并且变量在内核之间共享,这个问题的答案是否会改变? (assuming a shared cache between cores)
(假设内核之间共享缓存)
Thanks!谢谢!
A mutex protects you from more than just tearing - for example some ARM implementations use out-of-order execution, and a mutex will include memory (and compiler) barriers that may be necessary for your algorithm's correctness.互斥锁不仅可以保护您免受撕裂 - 例如,某些 ARM 实现使用乱序执行,互斥锁将包括 memory(和编译器)屏障,这可能是您的算法正确性所必需的。
It is safer to include the mutex, then figure out a way to optimise it later if it shows as a performance problem.包含互斥锁更安全,然后如果它显示为性能问题,然后找出一种方法来优化它。
Note also that if your compiler is GCC-based, you may have access to the GCC atomic builtins .另请注意,如果您的编译器是基于 GCC 的,您可能有权访问GCC atomic builtins 。
If all the writing is done from one thread (ie other threads are only reading), then no you don't need a mutex.如果所有写入都是从一个线程完成的(即其他线程只在读取),那么不,您不需要互斥锁。 If more than one thread may be writing, then you do.
如果可能有多个线程正在写入,那么您会这样做。
You don't need mutex.你不需要互斥锁。 On 32-bit ARM, single write or read is an atomic operation.
在 32 位 ARM 上,单次写入或读取是原子操作。 (regardless of the number of cores) Of course, you should declare that variable as volatile.
(无论内核数量如何)当然,您应该将该变量声明为 volatile。
On a 32-bit system, reads and writes of 32-bit vars are atomic.在 32 位系统上,32 位变量的读取和写入是原子的。 However, it depends what else you are doing with the variable.
但是,这取决于您对变量所做的其他操作。 Eg if you maniputale it somehow (eg add a value), then this requires a read, manipulation and write.
例如,如果您以某种方式对其进行操作(例如添加一个值),那么这需要读取、操作和写入。 If the CPU and compiler do not support an atomic operation for this, then you will need to use a mutex to protect this multi-operation sequence.
如果 CPU 和编译器不支持原子操作,那么您将需要使用互斥锁来保护这个多操作序列。
There are other, lock-free techniques which can reduce the need for mutexes.还有其他无锁技术可以减少对互斥体的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.