license.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 1 | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
mmentovai@google.com | f5a4000 | 2008-08-09 01:19:43 +0900 | [diff] [blame] | 4 | |
| 5 | #include "base/condition_variable.h" |
| 6 | |
| 7 | #include <errno.h> |
| 8 | #include <sys/time.h> |
| 9 | |
| 10 | #include "base/lock.h" |
| 11 | #include "base/lock_impl.h" |
| 12 | #include "base/logging.h" |
| 13 | |
| 14 | ConditionVariable::ConditionVariable(Lock* user_lock) |
| 15 | : user_mutex_(user_lock->lock_impl()->os_lock()) { |
| 16 | int rv = pthread_cond_init(&condition_, NULL); |
| 17 | DCHECK(rv == 0); |
| 18 | } |
| 19 | |
| 20 | ConditionVariable::~ConditionVariable() { |
| 21 | int rv = pthread_cond_destroy(&condition_); |
| 22 | DCHECK(rv == 0); |
| 23 | } |
| 24 | |
| 25 | void ConditionVariable::Wait() { |
| 26 | int rv = pthread_cond_wait(&condition_, user_mutex_); |
| 27 | DCHECK(rv == 0); |
| 28 | } |
| 29 | |
| 30 | void ConditionVariable::TimedWait(const TimeDelta& max_time) { |
| 31 | int64 usecs = max_time.InMicroseconds(); |
| 32 | |
| 33 | // The timeout argument to pthread_cond_timedwait is in absolute time. |
| 34 | struct timeval now; |
| 35 | gettimeofday(&now, NULL); |
| 36 | |
mmentovai@google.com | f5a4000 | 2008-08-09 01:19:43 +0900 | [diff] [blame] | 37 | struct timespec abstime; |
mmentovai@google.com | 7ba78d7 | 2008-08-12 03:15:10 +0900 | [diff] [blame] | 38 | abstime.tv_sec = now.tv_sec + (usecs / Time::kMicrosecondsPerSecond); |
| 39 | abstime.tv_nsec = (now.tv_usec + (usecs % Time::kMicrosecondsPerSecond)) * |
| 40 | Time::kNanosecondsPerMicrosecond; |
| 41 | abstime.tv_sec += abstime.tv_nsec / Time::kNanosecondsPerSecond; |
| 42 | abstime.tv_nsec %= Time::kNanosecondsPerSecond; |
mmentovai@google.com | f5a4000 | 2008-08-09 01:19:43 +0900 | [diff] [blame] | 43 | DCHECK(abstime.tv_sec >= now.tv_sec); // Overflow paranoia |
| 44 | |
| 45 | int rv = pthread_cond_timedwait(&condition_, user_mutex_, &abstime); |
| 46 | DCHECK(rv == 0 || rv == ETIMEDOUT); |
| 47 | } |
| 48 | |
| 49 | void ConditionVariable::Broadcast() { |
| 50 | int rv = pthread_cond_broadcast(&condition_); |
| 51 | DCHECK(rv == 0); |
| 52 | } |
| 53 | |
| 54 | void ConditionVariable::Signal() { |
| 55 | int rv = pthread_cond_signal(&condition_); |
| 56 | DCHECK(rv == 0); |
| 57 | } |
license.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 58 | |