summaryrefslogtreecommitdiff
path: root/test/monitor/gtest_spinlock.cpp
blob: 6bf2aa70a33f775f032c819432403970e3079742 (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
#include <unistd.h>
#include <pthread.h>
#include <getopt.h>
#include <gtest/gtest.h>
#include "monitor/monitor_private.h"

static volatile long sum = 0;
static volatile long barrier = 1;
#define CALC_NUM 10000000
static void *calc_thread(void *arg)
{
    stm_spinlock *lock = (stm_spinlock *)arg;
    (void)lock;
    while (barrier)
        ;
    for (int i = 0; i < CALC_NUM; i++)
    {
        stm_spinlock_lock(lock);
        sum++;
        stm_spinlock_unlock(lock);
    }

    return NULL;
}

TEST(MONITOR_SPINLOCK, base)
{
    pthread_t pid;
    stm_spinlock *lock = stm_spinlock_new();
    pthread_create(&pid, NULL, calc_thread, (void *)lock);
    usleep(5000);
    barrier = 0;
    for (int i = 0; i < CALC_NUM; i++)
    {
        stm_spinlock_lock(lock);
        sum++;
        stm_spinlock_unlock(lock);
    }
    pthread_join(pid, NULL);
    stm_spinlock_free(lock);
    EXPECT_EQ(sum, CALC_NUM * 2);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    int ret = RUN_ALL_TESTS();
    return ret;
}