I'm trying to create a BakeryLock abstraction using Lamport's bakery algorithm and Lockable concept from C++. It's quite easy to implement lock(), unlock() methods. Could someone help me with an implementation of the try_lock() method?
From documentation:
m.try_lock()
Effects: Attempts to acquire a lock for the current execution agent without blocking. If an exception is thrown, then a lock shall not have been acquired for the current execution agent.
Return type: bool
Returns: true if the lock was acquired, false otherwise.
I have come up with the following solution in C++, but haven't tested it fully yet.
bool ImprovedBakeryLock::try_lock(int i)
{
Entering[i] = true;
Number[i] = 1 + max(Number[1], ..., Number[NUM_THREADS]);
Entering[i] = false;
bool acquired = true;
for (int j = 1; j <= NUM_THREADS && acquired; ++j) {
if (Number[j] != 0 && Number[j] < Number[i]){
acquired = false;
Number[i] = 0;
}
}
return acquired;
}