view src/parallel_execution/SemaphoreImpl.cbc @ 468:ac244346c85d

Change used interface syntax from #include to #interface
author Tatsuki IHA <innparusu@cr.ie.u-ryukyu.ac.jp>
date Mon, 25 Dec 2017 18:10:56 +0900
parents 8d7e5d48cad3
children
line wrap: on
line source

#include "../context.h"
#interface "semaphore.h"

Semaphore* createSemaphoreImpl(struct Context* context, int n) {
    struct Semaphore* semaphore = new Semaphore();
    struct SemaphoreImpl* semaphoreImpl = new SemaphoreImpl();
    semaphore->semaphore = (union Data*)semaphoreImpl;
    semaphoreImpl->value =  n;
    pthread_mutex_init(&semaphoreImpl->mutex, NULL);
    pthread_cond_init(&semaphoreImpl->cond, NULL);
    semaphore->p = C_pOperationSemaphoreImpl;
    semaphore->v = C_vOperationSemaphoreImpl;
    return semaphore;
}

__code pOperationSemaphoreImpl(struct SemaphoreImpl* semaphore, __code next(...)) {
    pthread_mutex_lock(&semaphore->mutex);
    goto meta(context, C_pOperationSemaphoreImpl1);
}

__code pOperationSemaphoreImpl1(struct SemaphoreImpl* semaphore, __code next(...)) {
    if(semaphore->value == 0) {
        pthread_cond_wait(&semaphore->cond, &semaphore->mutex);
        goto meta(context, C_pOperationSemaphoreImpl1);
    }
    semaphore->value--;
    pthread_mutex_unlock(&semaphore->mutex);
    goto next(...);
}

__code vOperationSemaphoreImpl(struct SemaphoreImpl* semaphore, __code next(...)) {
    pthread_mutex_lock(&semaphore->mutex);
    semaphore->value++;
    pthread_cond_signal(&semaphore->cond);
    pthread_mutex_unlock(&semaphore->mutex);
    goto next(...);
}