I am reading a POSIX multi-threaded book for some practice, and I was trying to figure out where I would need the mutex guards in a simple single 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;
and I had two or more threads. Any stream can insert, delete, or read anywhere in the list.
It seems that if you just try to protect individual elements of the list (and not the entire list), you can never guarantee that another thread will not change the one pointed to by the following pointer *, so you cannot guarantee the safety and maintenance of invariants.
Is there a more effective way to protect this list than to do all operations with it with the same mutex? I would think that there is, but I really can’t think about it.
Also, if it was a doubly linked list, has the situation changed?
source share