Line data Source code
1 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 : /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 : // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
4 : // Use of this source code is governed by a BSD-style license that can be
5 : // found in the LICENSE file.
6 :
7 : #include "base/at_exit.h"
8 : #include "base/logging.h"
9 :
10 : namespace base {
11 :
12 : // Keep a stack of registered AtExitManagers. We always operate on the most
13 : // recent, and we should never have more than one outside of testing, when we
14 : // use the shadow version of the constructor. We don't protect this for
15 : // thread-safe access, since it will only be modified in testing.
16 : static AtExitManager* g_top_manager = NULL;
17 :
18 3 : AtExitManager::AtExitManager() : next_manager_(NULL) {
19 3 : DCHECK(!g_top_manager);
20 3 : g_top_manager = this;
21 3 : }
22 :
23 0 : AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
24 0 : DCHECK(shadow || !g_top_manager);
25 0 : g_top_manager = this;
26 0 : }
27 :
28 0 : AtExitManager::~AtExitManager() {
29 0 : if (!g_top_manager) {
30 0 : NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
31 0 : return;
32 : }
33 0 : DCHECK(g_top_manager == this);
34 :
35 0 : ProcessCallbacksNow();
36 0 : g_top_manager = next_manager_;
37 0 : }
38 :
39 : // static
40 3 : void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
41 3 : if (!g_top_manager) {
42 0 : NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
43 0 : return;
44 : }
45 :
46 3 : DCHECK(func);
47 :
48 6 : AutoLock lock(g_top_manager->lock_);
49 3 : g_top_manager->stack_.push(CallbackAndParam(func, param));
50 : }
51 :
52 : // static
53 0 : void AtExitManager::ProcessCallbacksNow() {
54 0 : if (!g_top_manager) {
55 0 : NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
56 0 : return;
57 : }
58 :
59 0 : AutoLock lock(g_top_manager->lock_);
60 :
61 0 : while (!g_top_manager->stack_.empty()) {
62 0 : CallbackAndParam callback_and_param = g_top_manager->stack_.top();
63 0 : g_top_manager->stack_.pop();
64 :
65 0 : callback_and_param.func_(callback_and_param.param_);
66 : }
67 : }
68 :
69 : // static
70 3 : bool AtExitManager::AlreadyRegistered() {
71 3 : return !!g_top_manager;
72 : }
73 :
74 : } // namespace base
|