Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy should Next() operation of a singly linked list be protected with a critical section?
    primarykey
    data
    text
    <p>I'm reading the book <em>Multithreading Applications in Win32</em></p> <p>The book says <code>return node-&gt;next</code> will be compiled into separate machine instructions that would not be executed as an atomic operation, so <code>Next()</code> should also be protected by the critical section. </p> <p>My question is, what instructions could it be translated into, to cause a race condition?</p> <pre><code>typedef struct _Node { struct Node *next; int data; } Node; typedef struct _List { Node *head; CRITICAL SECTION critical_sec; } List; List *CreateList() { List *pList = malloc(sizeof(List)); pList-&gt;head = NULL; InitializeCriticalSection(&amp;pList-&gt;critical_sec); return pList; } void DeleteList(List *pList) { DeleteCriticalSection(&amp;pList-&gt;critical_sec); free(pList); } void AddHead(List *pList, Node *node) { EnterCriticalSection(&amp;pList-&gt;critical_sec); node-&gt;next = pList-&gt;head; pList-&gt;head = node; LeaveCriticalSection(&amp;pList-&gt;critical_sec); } void Insert(List *pList, Node *afterNode, Node *newNode) { EnterCriticalSection(&amp;pList-&gt;critical_sec); if (afterNode == NULL) { AddHead(pList, newNode); } else { newNode-&gt;next = afterNode-&gt;next; afterNode-&gt;next = newNode; } LeaveCriticalSection(&amp;pList-&gt;critical_sec); } Node *Next(List *pList, Node *node) { Node* next; EnterCriticalSection(&amp;pList-&gt;critical_sec); next = node-&gt;next; LeaveCriticalSection(&amp;pList-&gt;critical_sec); return next; } </code></pre> <p><strong>Edit:</strong></p> <p>OK, although in this particular case it won't corrupt the singly linked list w/o protecting the <code>Next()</code> operation, a shared structure should be protected as a whole or nothing, generally.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload