blob: 1e31b1457681dd2cec1117fb91c3694c9323f1c7 [file] [log] [blame]
brettw@chromium.org61391822011-01-01 05:02:16 +09001// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
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
brettw@chromium.org61391822011-01-01 05:02:16 +090015#ifndef BASE_SPIN_WAIT_H_
16#define BASE_SPIN_WAIT_H_
thakis@chromium.org01d14522010-07-27 08:08:24 +090017#pragma once
initial.commit3f4a7322008-07-27 06:49:38 +090018
brettw@chromium.org61391822011-01-01 05:02:16 +090019#include "base/threading/platform_thread.h"
initial.commit3f4a7322008-07-27 06:49:38 +090020#include "base/time.h"
21
22// Provide a macro that will wait no longer than 1 second for an asynchronous
23// change is the value of an expression.
24// A typical use would be:
25//
26// SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(0 == f(x));
27//
28// The expression will be evaluated repeatedly until it is true, or until
29// the time (1 second) expires.
30// Since tests generally have a 5 second watch dog timer, this spin loop is
31// typically used to get the padding needed on a given test platform to assure
32// that the test passes, even if load varies, and external events vary.
33
34#define SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(expression) \
dsh@google.com0f8dd262008-10-28 05:43:33 +090035 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(base::TimeDelta::FromSeconds(1), \
36 (expression))
initial.commit3f4a7322008-07-27 06:49:38 +090037
38#define SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(delta, expression) do { \
jar@chromium.org25f1e9a2010-05-11 01:35:47 +090039 base::TimeTicks start = base::TimeTicks::Now(); \
dsh@google.com0f8dd262008-10-28 05:43:33 +090040 const base::TimeDelta kTimeout = delta; \
erg@google.combf6ce9f2010-01-27 08:08:02 +090041 while (!(expression)) { \
jar@chromium.org25f1e9a2010-05-11 01:35:47 +090042 if (kTimeout < base::TimeTicks::Now() - start) { \
43 EXPECT_LE((base::TimeTicks::Now() - start).InMilliseconds(), \
initial.commit3f4a7322008-07-27 06:49:38 +090044 kTimeout.InMilliseconds()) << "Timed out"; \
45 break; \
46 } \
brettw@chromium.org61391822011-01-01 05:02:16 +090047 base::PlatformThread::Sleep(50); \
initial.commit3f4a7322008-07-27 06:49:38 +090048 } \
erg@google.combf6ce9f2010-01-27 08:08:02 +090049 } while (0)
initial.commit3f4a7322008-07-27 06:49:38 +090050
brettw@chromium.org61391822011-01-01 05:02:16 +090051#endif // BASE_SPIN_WAIT_H_