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.
4 :
5 : #include "base/at_exit.h"
6 : #include "base/logging.h"
7 :
8 : namespace base {
9 :
10 : // Keep a stack of registered AtExitManagers. We always operate on the most
11 : // recent, and we should never have more than one outside of testing, when we
12 : // use the shadow version of the constructor. We don't protect this for
13 : // thread-safe access, since it will only be modified in testing.
14 : static AtExitManager* g_top_manager = NULL;
15 :
16 1420 : AtExitManager::AtExitManager() : next_manager_(NULL) {
17 1420 : DCHECK(!g_top_manager);
18 1420 : g_top_manager = this;
19 1420 : }
20 :
21 0 : AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
22 0 : DCHECK(shadow || !g_top_manager);
23 0 : g_top_manager = this;
24 0 : }
25 :
26 4257 : AtExitManager::~AtExitManager() {
27 1419 : if (!g_top_manager) {
28 0 : NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
29 : return;
30 : }
31 1419 : DCHECK(g_top_manager == this);
32 :
33 1419 : ProcessCallbacksNow();
34 2838 : g_top_manager = next_manager_;
35 1419 : }
36 :
37 : // static
38 4262 : void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
39 4262 : if (!g_top_manager) {
40 0 : NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
41 0 : return;
42 : }
43 :
44 4262 : DCHECK(func);
45 :
46 8524 : AutoLock lock(g_top_manager->lock_);
47 4262 : g_top_manager->stack_.push(CallbackAndParam(func, param));
48 : }
49 :
50 : // static
51 1419 : void AtExitManager::ProcessCallbacksNow() {
52 1419 : if (!g_top_manager) {
53 0 : NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
54 0 : return;
55 : }
56 :
57 2838 : AutoLock lock(g_top_manager->lock_);
58 :
59 7095 : while (!g_top_manager->stack_.empty()) {
60 4257 : CallbackAndParam callback_and_param = g_top_manager->stack_.top();
61 4257 : g_top_manager->stack_.pop();
62 :
63 4257 : callback_and_param.func_(callback_and_param.param_);
64 : }
65 : }
66 :
67 : // static
68 1419 : bool AtExitManager::AlreadyRegistered() {
69 1419 : return !!g_top_manager;
70 : }
71 :
72 : } // namespace base
|