1 // 2 // detail/win_global.hpp 3 // ~~~~~~~~~~~~~~~~~~~~~ 4 // 5 // Copyright (c) 2003-2021 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 11 #ifndef BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP 12 #define BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP 13 14 #if defined(_MSC_VER) && (_MSC_VER >= 1200) 15 # pragma once 16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) 17 18 #include <boost/asio/detail/config.hpp> 19 #include <boost/asio/detail/static_mutex.hpp> 20 #include <boost/asio/detail/tss_ptr.hpp> 21 22 #include <boost/asio/detail/push_options.hpp> 23 24 namespace boost { 25 namespace asio { 26 namespace detail { 27 28 template <typename T> 29 struct win_global_impl 30 { 31 // Destructor automatically cleans up the global. ~win_global_implboost::asio::detail::win_global_impl32 ~win_global_impl() 33 { 34 delete ptr_; 35 } 36 37 static win_global_impl instance_; 38 static static_mutex mutex_; 39 T* ptr_; 40 static tss_ptr<T> tss_ptr_; 41 }; 42 43 template <typename T> 44 win_global_impl<T> win_global_impl<T>::instance_ = { 0 }; 45 46 template <typename T> 47 static_mutex win_global_impl<T>::mutex_ = BOOST_ASIO_STATIC_MUTEX_INIT; 48 49 template <typename T> 50 tss_ptr<T> win_global_impl<T>::tss_ptr_; 51 52 template <typename T> win_global()53T& win_global() 54 { 55 if (static_cast<T*>(win_global_impl<T>::tss_ptr_) == 0) 56 { 57 win_global_impl<T>::mutex_.init(); 58 static_mutex::scoped_lock lock(win_global_impl<T>::mutex_); 59 if (win_global_impl<T>::instance_.ptr_ == 0) 60 win_global_impl<T>::instance_.ptr_ = new T; 61 win_global_impl<T>::tss_ptr_ = win_global_impl<T>::instance_.ptr_; 62 } 63 64 return *win_global_impl<T>::tss_ptr_; 65 } 66 67 } // namespace detail 68 } // namespace asio 69 } // namespace boost 70 71 #include <boost/asio/detail/pop_options.hpp> 72 73 #endif // BOOST_ASIO_DETAIL_WIN_GLOBAL_HPP 74