aboutsummaryrefslogtreecommitdiff
path: root/src/Platform/Posix/Mutex.c
blob: 72c28b24c2b8c6de43e98c6ab18e887d895c471a (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
#include "Thread.h"

#include <stdlib.h>
#include <errno.h>


BH_Mutex *BH_MutexNew(void)
{
    BH_Mutex *mutex;

    /* Allocate space for mutex and initialize it */
    mutex = malloc(sizeof(BH_Mutex));
    if (mutex && pthread_mutex_init(&mutex->handle, NULL))
    {
        free(mutex);
        return NULL;
    }

    return mutex;
}


void BH_MutexFree(BH_Mutex *mutex)
{
    pthread_mutex_destroy(&mutex->handle);
    free(mutex);
}


int BH_MutexLock(BH_Mutex *mutex)
{
    if (pthread_mutex_lock(&mutex->handle))
        return BH_ERROR;

    return BH_OK;
}


int BH_MutexUnlock(BH_Mutex *mutex)
{
    if (pthread_mutex_unlock(&mutex->handle))
        return BH_ERROR;

    return BH_OK;
}


int BH_MutexTryLock(BH_Mutex *mutex)
{
    switch (pthread_mutex_trylock(&mutex->handle))
    {
    case 0: return BH_OK;
    case EBUSY: return BH_TIMEOUT;
    default: return BH_ERROR;
    }
}