view src/parallel_execution/SynchronizedQueue.cbc @ 401:408b4aab7610

Supported par goto iterate statement for perl script
author Tatsuki IHA <innparusu@cr.ie.u-ryukyu.ac.jp>
date Tue, 29 Aug 2017 21:50:57 +0900
parents a2c01ab30ea2
children 0c024ea61601
line wrap: on
line source

#include "../context.h"

#include <stdio.h>

/* 
 * Nonnon-blocking queue of Paper: Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms(https://www.research.ibm.com/people/m/michael/podc-1996.pdf).
 */

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

__code clearSynchronizedQueue(struct SynchronizedQueue* queue, __code next(...)) {
    struct Element* top = queue->top;
    if (__sync_bool_compare_and_swap(&queue->top, top, NULL)) {
        goto next(...);
    } else {
        goto meta(context, C_clearSynchronizedQueue);
    }
}

__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 meta(context, C_putSynchronizedQueue);
    }
    if (nextElement == NULL) {
        if (__sync_bool_compare_and_swap(&last->next, nextElement, element)) {
            __sync_bool_compare_and_swap(&queue->last, last, element);
            goto next(...);
        }
    } else {
        __sync_bool_compare_and_swap(&queue->last, last, nextElement);
    }
    goto meta(context, C_putSynchronizedQueue);
}

__code takeSynchronizedQueue(struct SynchronizedQueue* queue, __code next(union Data* data, ...)) {
    struct Element* top = queue->top;
    struct Element* last = queue->last;
    struct Element* nextElement = top->next;
    if (top != queue->top) {
        goto meta(context, C_takeSynchronizedQueue);
    }
    if (top == last) {
        if (nextElement != NULL) {
          __sync_bool_compare_and_swap(&queue->last, last, nextElement);
        }
    } else {
        if (__sync_bool_compare_and_swap(&queue->top, top, nextElement)) {
            data = nextElement->data;
            goto next(data, ...);
        }
    }
    goto meta(context, C_takeSynchronizedQueue);
}

__code isEmptySynchronizedQueue(struct SynchronizedQueue* queue, __code next(...), __code whenEmpty(...)) {
    if (queue->top)
        goto next(...);
    else
        goto whenEmpty(...);
}