summaryrefslogtreecommitdiff
path: root/source/tests/mutex.test.c
blob: 9261fb1a58a4299b1157e30e6b7b99722841a8ac (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
74
75
76
77
78
79
80
81
82
83
84
#include "../kit/threads.h"

#define KIT_TEST_FILE mutex
#include "../kit/test.h"

enum {
  TEST_MUTEX_SLEEP        = 400000000,
  TEST_MUTEX_TICK_COUNT   = 200,
  TEST_MUTEX_THREAD_COUNT = 100,
};

typedef struct {
  mtx_t lock;
  int   value;
} mtx_test_data_t;

static int mtx_test_run(void *data) {
  int              i;
  mtx_test_data_t *x = (mtx_test_data_t *) data;
  for (i = 0; i < TEST_MUTEX_TICK_COUNT; i++) {
    mtx_lock(&x->lock);

    x->value += i;
    thrd_yield();
    x->value -= i + 42;
    thrd_yield();
    x->value += i + 20;
    thrd_yield();
    x->value += 22 - i;

    mtx_unlock(&x->lock);
  }
  return 0;
}

TEST("mutex lock") {
  ptrdiff_t i;

  mtx_test_data_t data;
  thrd_t          pool[TEST_MUTEX_THREAD_COUNT];
  data.value = 42;
  REQUIRE(mtx_init(&data.lock, mtx_plain) == thrd_success);

  for (i = 0; i < TEST_MUTEX_THREAD_COUNT; i++)
    thrd_create(pool + i, mtx_test_run, &data);
  for (i = 0; i < TEST_MUTEX_THREAD_COUNT; i++) thrd_join(pool[i], NULL);

  mtx_destroy(&data.lock);
  REQUIRE(data.value == 42);
}

static int test_lock(void *data) {
  mtx_t *m = (mtx_t *) data;
  mtx_lock(m);

  struct timespec sec = { .tv_sec = 0, .tv_nsec = TEST_MUTEX_SLEEP };
  thrd_sleep(&sec, NULL);

  mtx_unlock(m);

  return 0;
}

TEST("mutex try lock") {
  mtx_t m;
  REQUIRE(mtx_init(&m, mtx_plain) == thrd_success);

  thrd_t t;
  REQUIRE(thrd_create(&t, test_lock, &m) == thrd_success);

  struct timespec sec = { .tv_sec = 0, .tv_nsec = TEST_MUTEX_SLEEP / 2 };
  REQUIRE(thrd_sleep(&sec, NULL) == thrd_success);

  REQUIRE(mtx_trylock(&m) == thrd_busy);

  REQUIRE(thrd_join(t, NULL) == thrd_success);

  REQUIRE(mtx_trylock(&m) == thrd_success);
  REQUIRE(mtx_unlock(&m) == thrd_success);

  mtx_destroy(&m);
}

#undef KIT_TEST_FILE