posix_tss_ptr.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // posix_tss_ptr.hpp
  3. // ~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2008 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_TSS_PTR_HPP
  11. #define BOOST_ASIO_DETAIL_POSIX_TSS_PTR_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/push_options.hpp>
  16. #include <boost/asio/detail/push_options.hpp>
  17. #include <boost/config.hpp>
  18. #include <boost/system/system_error.hpp>
  19. #include <boost/asio/detail/pop_options.hpp>
  20. #if defined(BOOST_HAS_PTHREADS)
  21. #include <boost/asio/detail/push_options.hpp>
  22. #include <boost/throw_exception.hpp>
  23. #include <pthread.h>
  24. #include <boost/asio/detail/pop_options.hpp>
  25. #include <boost/asio/error.hpp>
  26. #include <boost/asio/detail/noncopyable.hpp>
  27. namespace boost {
  28. namespace asio {
  29. namespace detail {
  30. template <typename T>
  31. class posix_tss_ptr
  32. : private noncopyable
  33. {
  34. public:
  35. // Constructor.
  36. posix_tss_ptr()
  37. {
  38. int error = ::pthread_key_create(&tss_key_, 0);
  39. if (error != 0)
  40. {
  41. boost::system::system_error e(
  42. boost::system::error_code(error,
  43. boost::asio::error::get_system_category()),
  44. "tss");
  45. boost::throw_exception(e);
  46. }
  47. }
  48. // Destructor.
  49. ~posix_tss_ptr()
  50. {
  51. ::pthread_key_delete(tss_key_);
  52. }
  53. // Get the value.
  54. operator T*() const
  55. {
  56. return static_cast<T*>(::pthread_getspecific(tss_key_));
  57. }
  58. // Set the value.
  59. void operator=(T* value)
  60. {
  61. ::pthread_setspecific(tss_key_, value);
  62. }
  63. private:
  64. // Thread-specific storage to allow unlocked access to determine whether a
  65. // thread is a member of the pool.
  66. pthread_key_t tss_key_;
  67. };
  68. } // namespace detail
  69. } // namespace asio
  70. } // namespace boost
  71. #endif // defined(BOOST_HAS_PTHREADS)
  72. #include <boost/asio/detail/pop_options.hpp>
  73. #endif // BOOST_ASIO_DETAIL_POSIX_TSS_PTR_HPP