blob: e467c5d2b3f52529fc15af7a56e3e3b0711ad6af [file] [log] [blame]
jhawkins@chromium.org8e73d062011-04-05 03:04:37 +09001// Copyright (c) 2011 The Chromium Authors. All rights reserved.
mmentovai@google.comaa13be62008-09-03 03:20:34 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/at_exit.h"
jhawkins@chromium.org8e73d062011-04-05 03:04:37 +09006
7#include <stddef.h>
8#include <ostream>
9
mmentovai@google.comaa13be62008-09-03 03:20:34 +090010#include "base/logging.h"
11
12namespace base {
13
14// Keep a stack of registered AtExitManagers. We always operate on the most
15// recent, and we should never have more than one outside of testing, when we
16// use the shadow version of the constructor. We don't protect this for
17// thread-safe access, since it will only be modified in testing.
18static AtExitManager* g_top_manager = NULL;
19
20AtExitManager::AtExitManager() : next_manager_(NULL) {
21 DCHECK(!g_top_manager);
22 g_top_manager = this;
23}
24
mmentovai@google.comaa13be62008-09-03 03:20:34 +090025AtExitManager::~AtExitManager() {
26 if (!g_top_manager) {
27 NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
28 return;
29 }
30 DCHECK(g_top_manager == this);
31
32 ProcessCallbacksNow();
33 g_top_manager = next_manager_;
34}
35
36// static
deanm@google.comf6299e72008-09-08 18:06:51 +090037void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
mmentovai@google.comaa13be62008-09-03 03:20:34 +090038 if (!g_top_manager) {
39 NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
40 return;
41 }
42
deanm@google.comf6299e72008-09-08 18:06:51 +090043 DCHECK(func);
44
mmentovai@google.comaa13be62008-09-03 03:20:34 +090045 AutoLock lock(g_top_manager->lock_);
deanm@google.comf6299e72008-09-08 18:06:51 +090046 g_top_manager->stack_.push(CallbackAndParam(func, param));
mmentovai@google.comaa13be62008-09-03 03:20:34 +090047}
48
49// static
50void AtExitManager::ProcessCallbacksNow() {
51 if (!g_top_manager) {
52 NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
53 return;
54 }
55
56 AutoLock lock(g_top_manager->lock_);
57
58 while (!g_top_manager->stack_.empty()) {
deanm@google.comf6299e72008-09-08 18:06:51 +090059 CallbackAndParam callback_and_param = g_top_manager->stack_.top();
mmentovai@google.comaa13be62008-09-03 03:20:34 +090060 g_top_manager->stack_.pop();
deanm@google.comf6299e72008-09-08 18:06:51 +090061
62 callback_and_param.func_(callback_and_param.param_);
mmentovai@google.comaa13be62008-09-03 03:20:34 +090063 }
64}
65
erg@google.com37c078e2011-01-11 09:50:59 +090066AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
67 DCHECK(shadow || !g_top_manager);
68 g_top_manager = this;
69}
70
mmentovai@google.comaa13be62008-09-03 03:20:34 +090071} // namespace base