Skip to content
Advertisement

How costly is a low contention mutex in terms of cpu

I have some C code (on Linux) that needs to run in a thread safe manner. It’s very low contention but I have to guard it to ensure correctness.

I have the option of using local variables to guard it (which will work based on how the code is written) but since I have a mutex variable, which is the better approach in terms of cpu usage?

As I expect nearly never to have any contention on the lock is acquiring and releasing mutex significantly more costly compared to checking, incrementing and decrementing a local variable ?

I use the mutex elsewhere so by not using it I am not saving any memory.

Advertisement

Answer

If the same data will be modified concurrent with access from another thread, you only have two options: locking or using an atomic data type. There is no such thing as “using local variables to guard it”. Of the two options you have, locking and atomics, the bulk of their runtime cost is memory (cache) synchronization with other cores and it should be roughly the same for either one of them. This is a nontrivial cost (on the order of tens of cycles most likely) but it’s not one you can opt out of; there’s no way to obtain correctness without it.

Advertisement