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:
- Add two sentinel nodes to the list for the
head
and tail
. Both these nodes have locks associated with them, and every new node will be added between the two of them.
- For ever function that traverses the list, you need to obtain a lock on the next node before you assign it to a
current
pointer. 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 a prev
pointer for traversal, you will keep the lock on that "previous" node until you re-assign the prev
pointer to the current
pointer.
- For adding a node, you will need to lock the two nodes that are going to be on either side of the node you're adding. So for instance, you would have a
prev
node pointer, and a current
node pointer. You would first lock the mutex on the prev
node, and then lock the mutex on the current
node, and add the new node in-between the prev
and current
node.
- If you are removing a node, you would again lock the mutex in the
prev
and current
node (in that order) and then you can remove the current
node.
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.
Since locking a single node is not thread-safe (one thread might try to insert after it, while another is busy deleting the next node), neither is locking a subset of the nodes. Your best bet is to use a global mutex for the entire list, unless you're willing to put some effort into developing a read-write lock
, which would at least allow several threads to read the list at the same time.
Since a doubly-linked list is an even more complicated structure, I would maintain the same advice.