Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fine grained locking

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++?

like image 743
Cartesius00 Avatar asked Jan 26 '12 22:01

Cartesius00


People also ask

What is fine grained locking?

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.

What are fine grained and coarse-grained locks?

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.

What are coarse-grained locks?

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.

What is hand over hand locking?

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.


1 Answers

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.

like image 83
Soup d'Campbells Avatar answered Nov 09 '22 07:11

Soup d'Campbells