1 /* 2 * Copyright (c) 2015, 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 25 #include "precompiled.hpp" 26 #include "utilities/debug.hpp" 27 #include "runtime/semaphore.hpp" 28 29 // Implements the limited, platform independent Semaphore API. 30 Semaphore::Semaphore(uint value) : _impl(value) {} 31 Semaphore::~Semaphore() {} 32 void Semaphore::signal(uint count) { _impl.signal(count); } 33 void Semaphore::wait() { _impl.wait(); } 34 35 /////////////// Unit tests /////////////// 36 37 #ifndef PRODUCT 38 39 static void test_semaphore_single_separate(uint count) { 40 Semaphore sem(0); 41 42 for (uint i = 0; i < count; i++) { 43 sem.signal(); 44 } 45 46 for (uint i = 0; i < count; i++) { 47 sem.wait(); 48 } 49 } 50 51 static void test_semaphore_single_combined(uint count) { 52 Semaphore sem(0); 53 54 for (uint i = 0; i < count; i++) { 55 sem.signal(); 56 sem.wait(); 57 } 58 } 59 60 static void test_semaphore_many(uint value, uint max, uint increments) { 61 Semaphore sem(value); 62 63 uint total = value; 64 65 for (uint i = value; i + increments <= max; i += increments) { 66 sem.signal(increments); 67 68 total += increments; 69 } 70 71 for (uint i = 0; i < total; i++) { 72 sem.wait(); 73 } 74 } 75 76 static void test_semaphore_many() { 77 for (uint max = 0; max < 10; max++) { 78 for (uint value = 0; value < max; value++) { 79 for (uint inc = 1; inc <= max - value; inc++) { 80 test_semaphore_many(value, max, inc); 81 } 82 } 83 } 84 } 85 86 void test_semaphore() { 87 for (uint i = 1; i < 10; i++) { 88 test_semaphore_single_separate(i); 89 } 90 91 for (uint i = 0; i < 10; i++) { 92 test_semaphore_single_combined(i); 93 } 94 95 test_semaphore_many(); 96 } 97 98 #endif // PRODUCT 99