win_global.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // detail/win_global.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP
  11. #define BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #include <boost/asio/detail/static_mutex.hpp>
  17. #include <boost/asio/detail/tss_ptr.hpp>
  18. #include <boost/asio/detail/push_options.hpp>
  19. namespace boost {
  20. namespace asio {
  21. namespace detail {
  22. template <typename T>
  23. struct win_global_impl
  24. {
  25. // Destructor automatically cleans up the global.
  26. ~win_global_impl()
  27. {
  28. delete ptr_;
  29. }
  30. static win_global_impl instance_;
  31. static static_mutex mutex_;
  32. T* ptr_;
  33. static tss_ptr<T> tss_ptr_;
  34. };
  35. template <typename T>
  36. win_global_impl<T> win_global_impl<T>::instance_ = { 0 };
  37. template <typename T>
  38. static_mutex win_global_impl<T>::mutex_ = BOOST_ASIO_STATIC_MUTEX_INIT;
  39. template <typename T>
  40. tss_ptr<T> win_global_impl<T>::tss_ptr_;
  41. template <typename T>
  42. T& win_global()
  43. {
  44. if (static_cast<T*>(win_global_impl<T>::tss_ptr_) == 0)
  45. {
  46. win_global_impl<T>::mutex_.init();
  47. static_mutex::scoped_lock lock(win_global_impl<T>::mutex_);
  48. if (win_global_impl<T>::instance_.ptr_ == 0)
  49. win_global_impl<T>::instance_.ptr_ = new T;
  50. win_global_impl<T>::tss_ptr_ = win_global_impl<T>::instance_.ptr_;
  51. }
  52. return *win_global_impl<T>::tss_ptr_;
  53. }
  54. } // namespace detail
  55. } // namespace asio
  56. } // namespace boost
  57. #include <boost/asio/detail/pop_options.hpp>
  58. #endif // BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP