c++ - Why should Next() operation of a singly linked list be protected with a critical section? -
i'm reading book multithreading applications in win32
the book says return node->next compiled separate machine instructions not executed atomic operation, next() should protected critical section.
my question is, instructions translated into, cause race condition?
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->head = null; initializecriticalsection(&plist->critical_sec); return plist; } void deletelist(list *plist) { deletecriticalsection(&plist->critical_sec); free(plist); } void addhead(list *plist, node *node) { entercriticalsection(&plist->critical_sec); node->next = plist->head; plist->head = node; leavecriticalsection(&plist->critical_sec); } void insert(list *plist, node *afternode, node *newnode) { entercriticalsection(&plist->critical_sec); if (afternode == null) { addhead(plist, newnode); } else { newnode->next = afternode->next; afternode->next = newnode; } leavecriticalsection(&plist->critical_sec); } node *next(list *plist, node *node) { node* next; entercriticalsection(&plist->critical_sec); next = node->next; leavecriticalsection(&plist->critical_sec); return next; } edit:
ok, although in particular case won't corrupt singly linked list w/o protecting next() operation, shared structure should protected whole or nothing, generally.
return node->next performs 2 operations; first loads struct pointed node memory, looks @ node+offsetof(next) find pointer next, load register, , return calling program. contents of node may manipulated thread of execution in meantime.
Comments
Post a Comment