aboutsummaryrefslogtreecommitdiff
path: root/src/Platform/Posix/Semaphore.c
blob: 630475fe012112a4c145a250c46d8d72df5779e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "Thread.h"

#include <BH/Thread.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>


BH_Semaphore *BH_SemaphoreNew(int value)
{
    BH_Semaphore *semaphore;

    /* Allocate space for mutex and initialize it */
    semaphore = malloc(sizeof(BH_Semaphore));
    if (semaphore && sem_init(&semaphore->handle, 0, value))
    {
        free(semaphore);
        return NULL;
    }

    return semaphore;
}


void BH_SemaphoreFree(BH_Semaphore *semaphore)
{
    sem_destroy(&semaphore->handle);
    free(semaphore);
}


int BH_SemaphorePost(BH_Semaphore *semaphore)
{
    if (sem_post(&semaphore->handle))
        return BH_ERROR;

    return BH_OK;
}


int BH_SemaphoreWait(BH_Semaphore *semaphore)
{
    if (sem_wait(&semaphore->handle))
        return BH_ERROR;

    return BH_OK;
}


int BH_SemaphoreWaitTry(BH_Semaphore *semaphore)
{
    if (sem_trywait(&semaphore->handle))
        return BH_ERROR;

    return BH_OK;
}


int BH_SemaphoreWaitFor(BH_Semaphore *semaphore,
                        uint32_t timeout)
{
    struct timespec ts;

    ts.tv_sec = timeout / 1000;
    ts.tv_nsec = (timeout - ts.tv_sec * 1000) * 1000000;

    switch (sem_timedwait(&semaphore->handle, &ts))
    {
        case 0: return BH_OK;
        case ETIMEDOUT: return BH_TIMEOUT;
        default: return BH_ERROR;
    }
}