8183229: Implement WindowsSemaphore::trywait

Reviewed-by: redestad, stefank, kbarrett
This commit is contained in:
Mikael Gerdin 2017-06-30 10:36:32 +02:00
parent 19992b94e3
commit f21390e927
4 changed files with 31 additions and 1 deletions

View File

@ -1940,6 +1940,12 @@ void WindowsSemaphore::wait() {
assert(ret == WAIT_OBJECT_0, "WaitForSingleObject failed with return value: %lu", ret);
}
bool WindowsSemaphore::trywait() {
DWORD ret = ::WaitForSingleObject(_semaphore, 0);
assert(ret != WAIT_FAILED, "WaitForSingleObject failed with error code: %lu", GetLastError());
return ret == WAIT_OBJECT_0;
}
// sun.misc.Signal
// NOTE that this is a workaround for an apparent kernel bug where if
// a signal handler for SIGBREAK is installed then that signal handler

View File

@ -43,6 +43,8 @@ class WindowsSemaphore : public CHeapObj<mtInternal> {
void signal(uint count = 1);
void wait();
bool trywait();
};
typedef WindowsSemaphore SemaphoreImpl;

View File

@ -52,6 +52,8 @@ class Semaphore : public CHeapObj<mtInternal> {
void signal(uint count = 1) { _impl.signal(count); }
void wait() { _impl.wait(); }
bool trywait() { return _impl.trywait(); }
};

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -62,6 +62,18 @@ static void test_semaphore_many(uint value, uint max, uint increments) {
}
}
static void test_semaphore_trywait(uint value, uint max) {
Semaphore sem(value);
for (uint i = 0; i < max; ++i) {
if (i < value) {
ASSERT_EQ(sem.trywait(), true);
} else {
ASSERT_EQ(sem.trywait(), false);
}
}
}
TEST(Semaphore, single_separate) {
for (uint i = 1; i < 10; i++) {
test_semaphore_single_separate(i);
@ -83,3 +95,11 @@ TEST(Semaphore, many) {
}
}
}
TEST(Semaphore, trywait) {
for (uint max = 0; max < 10; max++) {
for (uint value = 0; value < max; value++) {
test_semaphore_trywait(value, max);
}
}
}