8183229: Implement WindowsSemaphore::trywait
authormgerdin
Fri, 30 Jun 2017 10:36:32 +0200
changeset 46610 d3e75e23b534
parent 46609 54423de91ff7
child 46612 c6b7c98e33ba
8183229: Implement WindowsSemaphore::trywait Reviewed-by: redestad, stefank, kbarrett
hotspot/src/os/windows/vm/os_windows.cpp
hotspot/src/os/windows/vm/semaphore_windows.hpp
hotspot/src/share/vm/runtime/semaphore.hpp
hotspot/test/native/runtime/test_semaphore.cpp
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Mon Jul 03 14:24:07 2017 +0200
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Fri Jun 30 10:36:32 2017 +0200
@@ -1940,6 +1940,12 @@
   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
--- a/hotspot/src/os/windows/vm/semaphore_windows.hpp	Mon Jul 03 14:24:07 2017 +0200
+++ b/hotspot/src/os/windows/vm/semaphore_windows.hpp	Fri Jun 30 10:36:32 2017 +0200
@@ -43,6 +43,8 @@
   void signal(uint count = 1);
 
   void wait();
+
+  bool trywait();
 };
 
 typedef WindowsSemaphore SemaphoreImpl;
--- a/hotspot/src/share/vm/runtime/semaphore.hpp	Mon Jul 03 14:24:07 2017 +0200
+++ b/hotspot/src/share/vm/runtime/semaphore.hpp	Fri Jun 30 10:36:32 2017 +0200
@@ -52,6 +52,8 @@
   void signal(uint count = 1) { _impl.signal(count); }
 
   void wait()                 { _impl.wait(); }
+
+  bool trywait()              { return _impl.trywait(); }
 };
 
 
--- a/hotspot/test/native/runtime/test_semaphore.cpp	Mon Jul 03 14:24:07 2017 +0200
+++ b/hotspot/test/native/runtime/test_semaphore.cpp	Fri Jun 30 10:36:32 2017 +0200
@@ -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_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, trywait) {
+  for (uint max = 0; max < 10; max++) {
+    for (uint value = 0; value < max; value++) {
+      test_semaphore_trywait(value, max);
+    }
+  }
+}