Adapt timedwait rather than implement trywait

This commit is contained in:
Axel Boldt-Christmas 2026-03-02 15:04:49 +00:00
parent 5c2313937e
commit 8a3be5ae35

View File

@ -73,24 +73,7 @@ void OSXSemaphore::wait() {
}
bool OSXSemaphore::trywait() {
kern_return_t kr = KERN_ABORTED;
// kernel semaphores take a relative timeout
mach_timespec_t waitspec;
waitspec.tv_sec = 0;
waitspec.tv_nsec = 0;
// Perform a semaphore_timedwait with a zero mach_timespec_t until we receive
// a result other than KERN_ABORTED.
while (kr == KERN_ABORTED) {
kr = semaphore_timedwait(_semaphore, waitspec);
}
assert(kr == KERN_SUCCESS || kr == KERN_OPERATION_TIMED_OUT,
"Failed to trywait on semaphore: %s (0x%x)",
sem_strerror(kr), (uint)kr);
return kr == KERN_SUCCESS;
return timedwait(0);
}
bool OSXSemaphore::timedwait(int64_t millis) {
@ -98,27 +81,37 @@ bool OSXSemaphore::timedwait(int64_t millis) {
// kernel semaphores take a relative timeout
mach_timespec_t waitspec;
int secs = millis / MILLIUNITS;
int nsecs = millis_to_nanos(millis % MILLIUNITS);
waitspec.tv_sec = secs;
waitspec.tv_nsec = nsecs;
int64_t starttime;
const bool is_trywait = millis == 0;
int64_t starttime = os::javaTimeNanos();
if (!is_trywait) {
int secs = millis / MILLIUNITS;
int nsecs = millis_to_nanos(millis % MILLIUNITS);
waitspec.tv_sec = secs;
waitspec.tv_nsec = nsecs;
starttime = os::javaTimeNanos();
} else {
waitspec.tv_sec = 0;
waitspec.tv_nsec = 0;
}
kr = semaphore_timedwait(_semaphore, waitspec);
while (kr == KERN_ABORTED) {
// reduce the timeout and try again
int64_t totalwait = millis_to_nanos(millis);
int64_t current = os::javaTimeNanos();
int64_t passedtime = current - starttime;
if (!is_trywait) {
// reduce the timeout and try again
int64_t totalwait = millis_to_nanos(millis);
int64_t current = os::javaTimeNanos();
int64_t passedtime = current - starttime;
if (passedtime >= totalwait) {
waitspec.tv_sec = 0;
waitspec.tv_nsec = 0;
} else {
int64_t waittime = totalwait - (current - starttime);
waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
if (passedtime >= totalwait) {
waitspec.tv_sec = 0;
waitspec.tv_nsec = 0;
} else {
int64_t waittime = totalwait - (current - starttime);
waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
}
}
kr = semaphore_timedwait(_semaphore, waitspec);