view Paper/src/SynchronizedQueue.cbc @ 33:c1323b737cfd

...
author matac42 <matac@cr.ie.u-ryukyu.ac.jp>
date Thu, 18 Jan 2024 19:37:19 +0900
parents c8151a82f313
children
line wrap: on
line source

#include "../context.h"
#interface "Queue.h"
#interface "Atomic.h"
#include <stdio.h>


Queue* createSynchronizedQueue(struct Context* context) {
    struct Queue* queue = new Queue();
    struct SynchronizedQueue* synchronizedQueue = new SynchronizedQueue();
    synchronizedQueue->top = new Element(); // allocate a free node
    synchronizedQueue->top->next = NULL;
    synchronizedQueue->last = synchronizedQueue->top;
    synchronizedQueue->atomic = createAtomicReference(context);
    queue->queue = (union Data*)synchronizedQueue;
    queue->take  = C_takeSynchronizedQueue;
    queue->put  = C_putSynchronizedQueue;
    queue->isEmpty = C_isEmptySynchronizedQueue;
    queue->clear = C_clearSynchronizedQueue;
    return queue;
}

__code putSynchronizedQueue(struct SynchronizedQueue* queue, union Data* data, __code next(...)) {
    Element* element = new Element();
    element->data = data;
    element->next = NULL;
    Element* last = queue->last;
    Element* nextElement = last->next;
    if (last != queue->last) {
        goto putSynchronizedQueue();
    }
    if (nextElement == NULL) {
        struct Atomic* atomic = queue->atomic;
        goto atomic->checkAndSet(&last->next, nextElement, element, next(...), putSynchronizedQueue);
    } else {
        struct Atomic* atomic = queue->atomic;
        goto atomic->checkAndSet(&queue->last, last, nextElement, putSynchronizedQueue, putSynchronizedQueue);
    }
}