![]() ![]() Here is the pop function:Ģ int lfstack_pop(_Atomic lfstack_t *lfstack)ħ if(orig.head = NULL) //return when the stack is emptyġ1 next.head = orig.head->next //set the head to the next nodeġ2 }while(!atomic_compare_exchange_weak(lfstack,&orig,next)) //if the head of stack is not changed, update the stackġ3 printf("poping value %d\n",orig.head->data) //just want to see the poping value.ġ4 free(orig.head) // free the poping node The pop function is also the same way of analyzing, and we let the analysis for students. If it has, you can loop and try again.ġ8 void lfstack_push(_Atomic lfstack_t *lfstack, int value)Ģ1 lfstack_t orig = atomic_load(lfstack) //here we need a local copy of lfstack, however, lfstack is a pointerĢ2 //we could not get the content from a struct pointer atomically by assignmentĢ3 //C11 provides us a function for us to atomically get the content from the location thatĢ5 Node *node = malloc(sizeof(Node)) //the new node, step 1Ģ9 next.head = node //local change of headģ0 }while(!atomic_compare_exchange_weak(lfstack,&orig,next)) //if the lfstack is not changed by others, apply the local change of head to it OK, so what can you do about this nasty race condition in a lock-free data-structure? The answer is to use an atomic compare and swap(CAS) operation to set the head node to point to your new node when CAS is sure that the head hasn’t been modified since you last read it. Let's see what would happen if two threads push a node into the stack concurrently. This works fine in a single-threaded context, but if other threads are also modifying the stack, it’s not enough. ![]() Let's see the process of pushing a node into a stack. ![]() We will implement a linked list lock-free stack by using the C11 knowledge we learnt before. Stack is a last in, first out(LIFO) data-structure. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |