cs431
cs431 copied to clipboard
[Question] [HW 3] fine-grained locks
When browsing through the nodes of the linked list, should I make sure the lock I acquire is not null before releasing the lock I had? For example if the part of the linked list is : ...->[A]->[B]->... - I currently have the lock A. - I try to get the lock to next (B) - I should do a while loop here to make sure I get the lock??? This was a question I had while implementing the find function of the cursor.
Are you talking about the raw pointer inside MutexGuard
for self
in Cursor::find
? Then yes, you should check if it is a null pointer, before you try to lock it. If it is null, then it means that you are at the end of the list, so find should return false
.
I recommend using ptr::as_ref()
Okay. So I should use the as_ref()
and treat the cases of pointer null and not null by using if some(...)
?
But then this works only for the cursor since it's a MutexGuard
. for the field next
in node
(which is a Mutex
) I don't think I can check that it's null before locking it using .lock()
I'm just asking because you said to check that it's not null, before I try to lock.
If you have just a Mutex
, since you are owning a type means it is valid.
The reason why you needed to null-check the value inside the MutexGuard
in Cursor::find()
is that what you get from the MutexGuard
is a raw pointer to Node<T>
, which may be null.
Once you have checked that the raw pointer points to valid memory and dereferenced to obtain node: Node<T>
is valid, node
is valid so you can just to node.next.lock()
.
Okay. I understand, but still how can I differentiate that with a null pointer that is due to an empty list or an element that should be inserted in the end of the list ...?
If the next node is null, you should be at the end of the list since you are holding the lock for the last node. The benefit of lock coupling is that there are no 'intermediate state' where you are at a node, and at the same time another thread is modifying it.