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?