I’m reading a POSIX threading book for some practice, and I was trying to work out where I’d need mutex guards in a simple singly-linked list as a little practice problem. For example, if I had a list of node structures:
template <typename T>
struct Node
{
Node<T>* next;
T data;
};
Node<T>* head = NULL;
//Populate list starting at head...
[HEAD] --> [NEXT] --> [NEXT] --> [NEXT] --> [...] --> [NULL]
and I had two or more threads. Any thread can insert, delete, or read at any point in the list.
It seems if you just try and guard individual list elements (and not the whole list), you can never guarantee another thread isn’t modifying the one the next* pointer points to, so you can’t guarantee safety and maintenance of invariants.
Is there any more efficient way to guard this list than making all operations on it use the same mutex? I would have thought there was but I really can’t think of it.
Also, if it were a doubly linked list does the situation change?
If you want to-do a fine-grained locking approach with a singly linked list (i.e., one lock per node), then you will need to-do the following:
headandtail. Both these nodes have locks associated with them, and every new node will be added between the two of them.currentpointer. You also cannot release the lock on the current node until you’ve obtained the lock on the next node. If you are also using aprevpointer for traversal, you will keep the lock on that “previous” node until you re-assign theprevpointer to thecurrentpointer.prevnode pointer, and acurrentnode pointer. You would first lock the mutex on theprevnode, and then lock the mutex on thecurrentnode, and add the new node in-between theprevandcurrentnode.prevandcurrentnode (in that order) and then you can remove thecurrentnode.Keep in mind that steps #3 and #4 work because of step #2 where traversing the list requires obtaining locks on the nodes. If you skip that step, you will end up creating dangling pointers and other problems related to mis-assigned pointers as another thread changes the topology of the list underneath the current thread.