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. |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 4 | |
| 5 | // This file provides a macro ONLY for use in testing. |
| 6 | // DO NOT USE IN PRODUCTION CODE. There are much better ways to wait. |
| 7 | |
| 8 | // This code is very helpful in testing multi-threaded code, without depending |
| 9 | // on almost any primitives. This is especially helpful if you are testing |
| 10 | // those primitive multi-threaded constructs. |
| 11 | |
| 12 | // We provide a simple one argument spin wait (for 1 second), and a generic |
| 13 | // spin wait (for longer periods of time). |
| 14 | |
| 15 | #ifndef BASE_SPIN_WAIT_H__ |
| 16 | #define BASE_SPIN_WAIT_H__ |
| 17 | |
paulg@google.com | 8964886 | 2008-08-23 06:49:05 +0900 | [diff] [blame] | 18 | #include "base/platform_thread.h" |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 19 | #include "base/time.h" |
| 20 | |
| 21 | // Provide a macro that will wait no longer than 1 second for an asynchronous |
| 22 | // change is the value of an expression. |
| 23 | // A typical use would be: |
| 24 | // |
| 25 | // SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(0 == f(x)); |
| 26 | // |
| 27 | // The expression will be evaluated repeatedly until it is true, or until |
| 28 | // the time (1 second) expires. |
| 29 | // Since tests generally have a 5 second watch dog timer, this spin loop is |
| 30 | // typically used to get the padding needed on a given test platform to assure |
| 31 | // that the test passes, even if load varies, and external events vary. |
| 32 | |
| 33 | #define SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(expression) \ |
| 34 | SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromSeconds(1), (expression)) |
| 35 | |
| 36 | #define SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(delta, expression) do { \ |
| 37 | Time start = Time::Now(); \ |
| 38 | const TimeDelta kTimeout = delta; \ |
| 39 | while(!(expression)) { \ |
| 40 | if (kTimeout < Time::Now() - start) { \ |
| 41 | EXPECT_LE((Time::Now() - start).InMilliseconds(), \ |
| 42 | kTimeout.InMilliseconds()) << "Timed out"; \ |
| 43 | break; \ |
| 44 | } \ |
paulg@google.com | 8964886 | 2008-08-23 06:49:05 +0900 | [diff] [blame] | 45 | PlatformThread::Sleep(50); \ |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 46 | } \ |
| 47 | } \ |
| 48 | while(0) |
| 49 | |
| 50 | #endif // BASE_SPIN_WAIT_H__ |
license.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 51 | |