Good day!
Recently, I peeped into courses an interesting version of working with lists in a multi-threaded environment, called this model there “fine synchronization”. The bottom line is that during the work with the list, access to the current and previous elements of the list is blocked for any operations like delete / insert, and at the same time there are no conflicts. Has anyone used this method of synchronization on real tasks?
Here is an example of adding an element to a linked list in pseudocode in courses:
Node prev = head; prev.lock(); Node curr = prev.next; curr.lock(); try{ while(curr.key < key){ prev.unlock(); prev = curr; curr = curr.next; curr.lock(); } if(key == curr.key) return false; else{ node = new Node(key,item); node.next = curr; pred.next = node; return true; } } finally{curr.unlock();pred.unlock();}
If we shift this example to C, then I have to create a list, the elements of which are instances of a certain structure containing a mutex. This is where I have the question of how to implement at least the first line of a given code without risking to catch a segfault when:
- the first thread received a pointer to the head element of the list,
- control got the second thread, and deleted the head element of the list,
- control returned to the first thread, it tries to capture the mutex of the head element of the list, which is no longer alive ...
?