BeeeOn Gateway
v2020.3.1-2-g6f737dc
Platform to interconnect the IoT world
|
#include <HashedLock.h>
Public Types | |
typedef LockType | Lock |
typedef Poco::SharedPtr < HashedLock< Lock, ID, Hash > > | Ptr |
Public Member Functions | |
HashedLock () | |
HashedLock (unsigned int count) | |
void | delayedInit (unsigned int count) |
Lock & | find (const ID &id) |
Lock & | at (const unsigned int index) |
unsigned int | size () const |
Protected Member Functions | |
void | assureInitialized () |
HashedLock is useful to reduce overhead of fine-grained locking strategy. If there are too many instances that should be locked during its processing and maintaining a separate lock for each instance would be expensive, this class can help to reduce this cost. The instances are sorted into buckets that share a single lock. The sorting is performed via a hash function. Thus, if the hash function has a low collision rate, the performance of this strategy would be very close to the fine-grained locking.
Common usage with Poco::FastMutex:
#define GOOD_PRIME 31 HashedLock<FastMutex, MyType, MyTypeHash> lock(GOOD_PRIME);
startThread(lock, threadWork); startThread(lock, threadWork); startThread(lock, threadWork);
void threadWork(auto &lock) { MyType &type = obtainOne(); FastMutex::ScopedLock guard(lock.find(type)); ... }
The probability of sharing a lock depends on the number of threads (usually fixed) and the quality of the used hash function.
BeeeOn::HashedLock< Lock, ID, Hash >::HashedLock | ( | ) |
Create zero lock instances. It must be allocated explicitly by calling delayedInit().
BeeeOn::HashedLock< Lock, ID, Hash >::HashedLock | ( | unsigned int | count | ) |
Create count lock instances.
Lock & BeeeOn::HashedLock< Lock, ID, Hash >::at | ( | const unsigned int | index | ) |
Return lock at the given index.
void BeeeOn::HashedLock< Lock, ID, Hash >::delayedInit | ( | unsigned int | count | ) |
Initializes the internal locks. This call can be called only once during its life time. Every other call would end up with Poco::InvalidAccessException.
Lock & BeeeOn::HashedLock< Lock, ID, Hash >::find | ( | const ID & | id | ) |
Find a lock for a given instance (or its identifier). The returned lock can be immediately used.
unsigned int BeeeOn::HashedLock< Lock, ID, Hash >::size | ( | ) | const |
Return count of real locks.