win_global.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // detail/win_global.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 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. static 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. T* win_global_impl<T>::ptr_ = 0;
  41. template <typename T>
  42. tss_ptr<T> win_global_impl<T>::tss_ptr_;
  43. template <typename T>
  44. T& win_global()
  45. {
  46. if (static_cast<T*>(win_global_impl<T>::tss_ptr_) == 0)
  47. {
  48. win_global_impl<T>::mutex_.init();
  49. static_mutex::scoped_lock lock(win_global_impl<T>::mutex_);
  50. win_global_impl<T>::ptr_ = new T;
  51. win_global_impl<T>::tss_ptr_ = win_global_impl<T>::ptr_;
  52. }
  53. return *win_global_impl<T>::tss_ptr_;
  54. }
  55. } // namespace detail
  56. } // namespace asio
  57. } // namespace boost
  58. #include <boost/asio/detail/pop_options.hpp>
  59. #endif // BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP