aboutsummaryrefslogtreecommitdiff
path: root/src/Platform/Spinlock.c
blob: aecb6ffaec0bb333121269ce26b26cf6f59968be (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
#include <BH/Thread.h>


#if defined(__clang__) || defined(__GNUC__)
/* Using built-ins */
#elif defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif


void BH_SpinlockLock(int *lock)
{
#if defined(__clang__) || defined(__GNUC__)
    while (__sync_lock_test_and_set(lock, 1));
#elif defined(_WIN32)
    while (InterlockedExchange(lock, 1));
#else
    #error "Spinlocks are not supported"
#endif
}


int BH_SpinlockTryLock(int *lock)
{
#if defined(__clang__) || defined(__GNUC__)
    if (__sync_lock_test_and_set(lock, 1))
        return BH_ERROR;
    return BH_OK;
#elif defined(_WIN32)
    if (InterlockedExchange(lock, 1))
        return BH_ERROR;
    return BH_OK;
#else
    #error "Spinlocks are not supported"
    return BH_NOIMPL;
#endif
}


void BH_SpinlockUnlock(int *lock)
{
#if defined(__clang__) || defined(__GNUC__)
    __sync_lock_release(lock);
#elif defined(_WIN32)
    InterlockedExchange(lock, 0);
#else
    #error "Spinlocks are not supported"
#endif
}