From 1fb04ff4e5d401d8a8caca2b4cd34706a883b536 Mon Sep 17 00:00:00 2001 From: Tom Cherry Date: Wed, 22 Feb 2017 17:38:00 -0800 Subject: Make Condition use CLOCK_MONOTONIC Changes to the REALTIME clock can cause Condition::waitRelative() to timeout early or delayed. This behavior is undesired and new since https://android-review.googlesource.com/#/c/181058/ moved the underlying pthread_cond_timedwait() implementation to use absolute timeouts rather than relative ones. Having Condition use CLOCK_MONOTONIC prevents these timeout issues. Bug: 34592766 Bug: 35678943 Test: Boot bullhead Test: Ensure time changes do not cause Condition::waitRelative() to timeout early or delayed Change-Id: I3a8d7a48f9b42fe990c3c7331313b6d85aa546f9 --- libutils/include/utils/Condition.h | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'libutils/include') diff --git a/libutils/include/utils/Condition.h b/libutils/include/utils/Condition.h index 25a53aa23..2c80acd5c 100644 --- a/libutils/include/utils/Condition.h +++ b/libutils/include/utils/Condition.h @@ -86,19 +86,22 @@ private: #if !defined(_WIN32) -inline Condition::Condition() { - pthread_cond_init(&mCond, NULL); +inline Condition::Condition() : Condition(PRIVATE) { } inline Condition::Condition(int type) { + pthread_condattr_t attr; + pthread_condattr_init(&attr); +#if defined(__linux__) + pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); +#endif + if (type == SHARED) { - pthread_condattr_t attr; - pthread_condattr_init(&attr); pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); - pthread_cond_init(&mCond, &attr); - pthread_condattr_destroy(&attr); - } else { - pthread_cond_init(&mCond, NULL); } + + pthread_cond_init(&mCond, &attr); + pthread_condattr_destroy(&attr); + } inline Condition::~Condition() { pthread_cond_destroy(&mCond); @@ -109,7 +112,7 @@ inline status_t Condition::wait(Mutex& mutex) { inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) { struct timespec ts; #if defined(__linux__) - clock_gettime(CLOCK_REALTIME, &ts); + clock_gettime(CLOCK_MONOTONIC, &ts); #else // __APPLE__ // Apple doesn't support POSIX clocks. struct timeval t; -- cgit v1.2.3