Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I mutex lock a single variable?

Tags:

c

embedded

If a single 32-bit variable is shared between multiple threads, should I put a mutex lock around the variable? For example, suppose 1 thread writes to a 32-bit counter and a 2nd thread reads it. Is there any chance the 2nd thread could read a corrupted value?

I'm working on a 32-bit ARM embedded system. The compiler always seems to align 32-bit variables so they can be read or written with a single instruction. 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.

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!

like image 469
Will Avatar asked Jul 01 '11 20:07

Will


2 Answers

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.

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.

like image 50
caf Avatar answered Nov 13 '22 14:11

caf


If all the writing is done from one thread (i.e. other threads are only reading), then no you don't need a mutex. If more than one thread may be writing, then you do.

like image 43
Graeme Perrow Avatar answered Nov 13 '22 15:11

Graeme Perrow