summaryrefslogtreecommitdiff
path: root/source/tests/thread.test.c
blob: 46c9597739978faa566ad33e30a85f7349222de8 (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
85
86
87
88
89
90
91
92
93
#include "../kit/thread.h"

#define KIT_TEST_FILE thread
#include "../kit/kit_test.h"

static int test_nothing(void *_) {
  return 0;
}

static int test_run(void *data) {
  int *n = (int *) data;
  return *n + 20;
}

static int test_exit(void *data) {
  int *n = (int *) data;

  *n = 1;
  thrd_exit(3);
  *n = 2;
  return 4;
}

static int test_yield(void *data) {
  thrd_yield();
  return 0;
}

static int test_sleep(void *data) {
  struct timespec t = { .tv_sec = 0, .tv_nsec = 10000000 };
  thrd_sleep(&t, NULL);
  return 0;
}

TEST("thread run") {
  thrd_t t;
  int    data = 22;
  int    result;
  REQUIRE(thrd_create(&t, test_run, &data) == thrd_success);
  REQUIRE(thrd_join(t, &result) == thrd_success);
  REQUIRE(result == 42);
}

TEST("thread stack size") {
  thrd_t foo;
  REQUIRE(thrd_create_with_stack(&foo, test_nothing, NULL, 30000) ==
          thrd_success);
  REQUIRE(thrd_join(foo, NULL) == thrd_success);
}

TEST("thread equal") {
  thrd_t foo, bar;
  REQUIRE(thrd_create(&foo, test_nothing, NULL) == thrd_success);
  REQUIRE(thrd_create(&bar, test_nothing, NULL) == thrd_success);
  REQUIRE(thrd_equal(foo, foo));
  REQUIRE(!thrd_equal(foo, bar));
  REQUIRE(!thrd_equal(foo, thrd_current()));
  REQUIRE(thrd_join(foo, NULL) == thrd_success);
  REQUIRE(thrd_join(bar, NULL) == thrd_success);
}

TEST("thread exit") {
  thrd_t foo;
  int    data;
  int    result;
  REQUIRE(thrd_create(&foo, test_exit, &data) == thrd_success);
  REQUIRE(thrd_join(foo, &result) == thrd_success);
  REQUIRE(data == 1);
  REQUIRE(result == 3);
}

TEST("thread yield") {
  thrd_t foo;
  REQUIRE(thrd_create(&foo, test_yield, NULL) == thrd_success);
  REQUIRE(thrd_join(foo, NULL) == thrd_success);
}

TEST("thread sleep") {
  thrd_t foo;
  REQUIRE(thrd_create(&foo, test_sleep, NULL) == thrd_success);
  REQUIRE(thrd_join(foo, NULL) == thrd_success);
}

TEST("thread detach") {
  thrd_t foo;
  REQUIRE(thrd_create(&foo, test_nothing, NULL) == thrd_success);
  REQUIRE(thrd_detach(foo) == thrd_success);

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

#undef KIT_TEST_FILE