view src/parallel_execution/SemaphoreImpl.cbc @ 286:fd470e090403

Add sempahore
author Tatsuki IHA <e125716@ie.u-ryukyu.ac.jp>
date Sun, 05 Feb 2017 22:15:27 +0900
parents
children b07078bd1f2c
line wrap: on
line source

#include "../context.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(...);
}