1/*
2 * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24#include "precompiled.hpp"
25#include "runtime/semaphore.hpp"
26#include "unittest.hpp"
27
28static void test_semaphore_single_separate(uint count) {
29  Semaphore sem(0);
30
31  for (uint i = 0; i < count; i++) {
32    sem.signal();
33  }
34
35  for (uint i = 0; i < count; i++) {
36    sem.wait();
37  }
38}
39
40static void test_semaphore_single_combined(uint count) {
41  Semaphore sem(0);
42
43  for (uint i = 0; i < count; i++) {
44    sem.signal();
45    sem.wait();
46  }
47}
48
49static void test_semaphore_many(uint value, uint max, uint increments) {
50  Semaphore sem(value);
51
52  uint total = value;
53
54  for (uint i = value; i + increments <= max; i += increments) {
55    sem.signal(increments);
56
57    total += increments;
58  }
59
60  for (uint i = 0; i < total; i++) {
61    sem.wait();
62  }
63}
64
65static void test_semaphore_trywait(uint value, uint max) {
66  Semaphore sem(value);
67
68  for (uint i = 0; i < max; ++i) {
69    if (i < value) {
70      ASSERT_EQ(sem.trywait(), true);
71    } else {
72      ASSERT_EQ(sem.trywait(), false);
73    }
74  }
75}
76
77TEST(Semaphore, single_separate) {
78  for (uint i = 1; i < 10; i++) {
79    test_semaphore_single_separate(i);
80  }
81}
82
83TEST(Semaphore, single_combined) {
84  for (uint i = 1; i < 10; i++) {
85    test_semaphore_single_combined(i);
86  }
87}
88
89TEST(Semaphore, many) {
90  for (uint max = 0; max < 10; max++) {
91    for (uint value = 0; value < max; value++) {
92      for (uint inc = 1; inc <= max - value; inc++) {
93        test_semaphore_many(value, max, inc);
94      }
95    }
96  }
97}
98
99TEST(Semaphore, trywait) {
100  for (uint max = 0; max < 10; max++) {
101    for (uint value = 0; value < max; value++) {
102      test_semaphore_trywait(value, max);
103    }
104  }
105}
106