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 : #ifndef BASE_AT_EXIT_H_
8 : #define BASE_AT_EXIT_H_
9 :
10 : #include <stack>
11 :
12 : #include "base/basictypes.h"
13 : #include "base/lock.h"
14 :
15 : namespace base {
16 :
17 : // This class provides a facility similar to the CRT atexit(), except that
18 : // we control when the callbacks are executed. Under Windows for a DLL they
19 : // happen at a really bad time and under the loader lock. This facility is
20 : // mostly used by base::Singleton.
21 : //
22 : // The usage is simple. Early in the main() or WinMain() scope create an
23 : // AtExitManager object on the stack:
24 : // int main(...) {
25 : // base::AtExitManager exit_manager;
26 : //
27 : // }
28 : // When the exit_manager object goes out of scope, all the registered
29 : // callbacks and singleton destructors will be called.
30 :
31 : class AtExitManager {
32 : protected:
33 : // This constructor will allow this instance of AtExitManager to be created
34 : // even if one already exists. This should only be used for testing!
35 : // AtExitManagers are kept on a global stack, and it will be removed during
36 : // destruction. This allows you to shadow another AtExitManager.
37 : explicit AtExitManager(bool shadow);
38 :
39 : public:
40 : typedef void (*AtExitCallbackType)(void*);
41 :
42 : AtExitManager();
43 :
44 : // The dtor calls all the registered callbacks. Do not try to register more
45 : // callbacks after this point.
46 : ~AtExitManager();
47 :
48 : // Registers the specified function to be called at exit. The prototype of
49 : // the callback function is void func().
50 : static void RegisterCallback(AtExitCallbackType func, void* param);
51 :
52 : // Calls the functions registered with RegisterCallback in LIFO order. It
53 : // is possible to register new callbacks after calling this function.
54 : static void ProcessCallbacksNow();
55 :
56 : static bool AlreadyRegistered();
57 :
58 : private:
59 : struct CallbackAndParam {
60 3 : CallbackAndParam(AtExitCallbackType func, void* param)
61 3 : : func_(func), param_(param) { }
62 : AtExitCallbackType func_;
63 : void* param_;
64 : };
65 :
66 : Lock lock_;
67 : std::stack<CallbackAndParam> stack_;
68 : AtExitManager* next_manager_; // Stack of managers to allow shadowing.
69 :
70 : DISALLOW_COPY_AND_ASSIGN(AtExitManager);
71 : };
72 :
73 : } // namespace base
74 :
75 : #endif // BASE_AT_EXIT_H_
|