Let's say we have a big array and many threads operating on concrete indexes in that array. Two threads cannot operate on one index at the same time, one should wait until the other finishes. And the lame question: How to implement test-and-set
locking on each index of the array in Linux/C/C++?
Fine grained locking is an experimental performance improvement for multithreaded workloads. It allows Vulkan calls from different threads to be validated in parallel, instead of being serialized by a global lock.
Coarse-grained systems consist of fewer, larger components than fine-grained systems; a coarse-grained description of a system regards large subcomponents while a fine-grained description regards smaller components of which the larger ones are composed.
A Coarse-Grained Lock is a single lock that covers many objects. It not only simplifies the locking action itself but also frees you from having to load all the members of a group in order to lock them.
Hand-over-hand locking 1 is a fine-grained synchronization technique that prevent data races among concurrent operations. Commonly applied to pointer-based data structures, operations lock nodes as they traverse the data structure.
For fine grained locking, use an array of read/write locks (as Carey Hickling suggests). Hash the index value and filter it through a bit mask (or use modulus) to select which lock to use.
This effectively splits the indexes into N buckets, where N is the number of locks you create. Choose a power of two for the number of locks for easy bit masking (mask = N - 1). The only drawback in this scenario is that you're not just locking a specific index, you're locking every index that, when hashed, aligns to the same lock pointer.
That being said, the more locks you create, the finer grained the locking is (16 is probably a good starting point). Read locks are shared with rw_locks as well, so you only have to worry about waiting for the lock during writes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With