posix_global.hpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // detail/posix_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. #ifndef BOOST_ASIO_DETAIL_POSIX_GLOBAL_HPP
  11. #define BOOST_ASIO_DETAIL_POSIX_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. #if defined(BOOST_ASIO_HAS_PTHREADS)
  17. #include <exception>
  18. #include <pthread.h>
  19. #include <boost/asio/detail/push_options.hpp>
  20. namespace boost {
  21. namespace asio {
  22. namespace detail {
  23. template <typename T>
  24. struct posix_global_impl
  25. {
  26. // Helper function to perform initialisation.
  27. static void do_init()
  28. {
  29. instance_.static_ptr_ = instance_.ptr_ = new T;
  30. }
  31. // Destructor automatically cleans up the global.
  32. ~posix_global_impl()
  33. {
  34. delete static_ptr_;
  35. }
  36. static ::pthread_once_t init_once_;
  37. static T* static_ptr_;
  38. static posix_global_impl instance_;
  39. T* ptr_;
  40. };
  41. template <typename T>
  42. ::pthread_once_t posix_global_impl<T>::init_once_ = PTHREAD_ONCE_INIT;
  43. template <typename T>
  44. T* posix_global_impl<T>::static_ptr_ = 0;
  45. template <typename T>
  46. posix_global_impl<T> posix_global_impl<T>::instance_;
  47. template <typename T>
  48. T& posix_global()
  49. {
  50. int result = ::pthread_once(
  51. &posix_global_impl<T>::init_once_,
  52. &posix_global_impl<T>::do_init);
  53. if (result != 0)
  54. std::terminate();
  55. return *posix_global_impl<T>::instance_.ptr_;
  56. }
  57. } // namespace detail
  58. } // namespace asio
  59. } // namespace boost
  60. #include <boost/asio/detail/pop_options.hpp>
  61. #endif // defined(BOOST_ASIO_HAS_PTHREADS)
  62. #endif // BOOST_ASIO_DETAIL_POSIX_GLOBAL_HPP