Roll breakpad a513e85:7caf028 (svn 1384:1385)
[chromium-blink-merge.git] / base / synchronization / spin_wait.h
blob9b147cda96544a4881ab4956cfaff7426d57567b
1 // Copyright (c) 2012 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.
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.
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.
12 // We provide a simple one argument spin wait (for 1 second), and a generic
13 // spin wait (for longer periods of time).
15 #ifndef BASE_SYNCHRONIZATION_SPIN_WAIT_H_
16 #define BASE_SYNCHRONIZATION_SPIN_WAIT_H_
18 #include "base/threading/platform_thread.h"
19 #include "base/time/time.h"
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:
25 // SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(0 == f(x));
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.
33 #define SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(expression) \
34 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(base::TimeDelta::FromSeconds(1), \
35 (expression))
37 #define SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(delta, expression) do { \
38 base::TimeTicks start = base::TimeTicks::Now(); \
39 const base::TimeDelta kTimeout = delta; \
40 while (!(expression)) { \
41 if (kTimeout < base::TimeTicks::Now() - start) { \
42 EXPECT_LE((base::TimeTicks::Now() - start).InMilliseconds(), \
43 kTimeout.InMilliseconds()) << "Timed out"; \
44 break; \
45 } \
46 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); \
47 } \
48 } while (0)
50 #endif // BASE_SYNCHRONIZATION_SPIN_WAIT_H_