summaryrefslogtreecommitdiff
path: root/infra/monitor/monitor_spinlock.c
blob: 9614803c18a02be9063e6321086c89f50877d18d (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
// https://www.cs.utexas.edu/~pingali/CS378/2015sp/lectures/Spinlocks%20and%20Read-Write%20Locks.htm
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stddef.h>
#include <pthread.h>

#if 0 /* use gcc builtin function  */
struct stm_spinlock
{
    long value;
};

struct stm_spinlock *stm_spinlock_new(void)
{
    struct stm_spinlock *splock = (struct stm_spinlock *)calloc(1, sizeof(struct stm_spinlock));
    return splock;
}

void stm_spinlock_lock(struct stm_spinlock *splock)
{
    while (__sync_lock_test_and_set(&splock->value, 1))
    {
    }
}

void stm_spinlock_unlock(struct stm_spinlock *splock)
{
    __sync_lock_release(&splock->value);
}

void stm_spinlock_free(struct stm_spinlock *splock)
{
    if (splock)
    {
        free(splock);
    }
}
#else /* pthread spin lock */
struct stm_spinlock
{
    pthread_spinlock_t lock_ins;
};

struct stm_spinlock *stm_spinlock_new(void)
{
    struct stm_spinlock *splock = (struct stm_spinlock *)calloc(1, sizeof(struct stm_spinlock));
    pthread_spin_init(&splock->lock_ins, PTHREAD_PROCESS_PRIVATE);
    return splock;
}

void stm_spinlock_lock(struct stm_spinlock *splock)
{
    pthread_spin_lock(&splock->lock_ins);
}

void stm_spinlock_unlock(struct stm_spinlock *splock)
{
    pthread_spin_unlock(&splock->lock_ins);
}

void stm_spinlock_free(struct stm_spinlock *splock)
{
    if (splock)
    {
        pthread_spin_destroy(&splock->lock_ins);
        free(splock);
    }
}
#endif