at_exit.h 2.3 KB

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