简体   繁体   中英

Do I need to use a mutex to protect access to an array of mutexes from different threads?

Let's say I have a bunch of files, and an array with a mutex for each file. Now I have different threads reading from random files, but first they need to acquire the lock from the array. Should I have a lock on the entire array that must be acquired before taking the mutex for the particular file?

No, but what you do is to bring the memory in which these mutexes live into every thread since you placed the mutexes close on purpose.

Keep the other threads accesses to memory away from what the other individual threads deal with.

Assosiate each thread with data as tightly packed (but aligned), and as in as few cache lines , as possible. One mutex and one data set - nowhere close to where the other working threads needs access.

You can easily measure the effect by using a homemade std::hardware_constructive_interference_size like ... 64 (popular, non-scientific, but common).

Separate the data in such a way that no other thread needs to touch data within those 64 (or whatever number you come up with) bytes.

It's a " no kidding? " experience.


The number 64 is almost arbitrary. I can compile a program using that constant - but it will not be translated into something meaningful for a different target platform - it'll stay 64. It's a best guess.

Understanding std::hardware_destructive_interference_size and std::hardware_constructive_interference_size

No, accessing different elements of an array in different threads does not cause data races and a mutex can be used by multiple threads unsynchronized, because it must be able to to fulfill its purpose.

You do not need to add a lock for the array itself. The same is true for member functions of standard library containers that only access elements and do not modify the container itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM