How could I implement this lock-free queue pseudocode in C
?
ENQUEUE(x)
q ← new record
q^.value ← x
q^.next ← NULL
repeat
p ← tail
succ ← COMPARE&SWAP(p^.next, NULL, q)
if succ ≠ TRUE
COMPARE&SWAP(tail, p, p^.next)
until succ = TRUE
COMPARE&SWAP(tail,p,q)
end
DEQUEUE()
repeat
p ← head
if p^.next = NULL
error queue empty
until COMPARE&SWAP(head, p, p^.next)
return p^.next^.value
end
How would be using the Built-in functions for atomic memory access
__sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)
I currently have
typedef struct queueelem {
queuedata_t data;
struct queueelem *next;
} queueelem_t;
typedef struct queue {
int capacity;
int size;
queueelem_t *head;
queueelem_t *tail;
} queue_t;
queue_t *
queue_init(int capacity)
{
queue_t *q = (queue_t *) malloc(sizeof(queue_t));
q->head = q->tail = NULL;
q->size = 0;
q->capacity = capacity;
return q;
}
_t
are reserved in some standards (POSIX, not sure about the actual standard) and shouldn't be used in your code. You should use a different naming convention. – Maidenhead