summaryrefslogtreecommitdiff
path: root/source/test/unittests/mutex.test.c
blob: 1bd2b3d05750c96e504d0787747b9ee113a90322 (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
#include "../../kit/mutex.h"
#include "../../kit/thread.h"

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

enum { SLEEP = 400000000, TICK_COUNT = 200, THREAD_COUNT = 100 };

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

static int test_run(void *data) {
  int          i;
  test_data_t *x = (test_data_t *) data;
  for (i = 0; i < 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;

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

  for (i = 0; i < THREAD_COUNT; i++)
    thrd_create(pool + i, test_run, &data);
  for (i = 0; i < 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 = 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 = 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);
}