tss.hpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #ifndef BOOST_THREAD_TSS_HPP
  2. #define BOOST_THREAD_TSS_HPP
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // (C) Copyright 2007-8 Anthony Williams
  7. #include <boost/thread/detail/config.hpp>
  8. #include <boost/type_traits/add_reference.hpp>
  9. #include <boost/config/abi_prefix.hpp>
  10. namespace boost
  11. {
  12. namespace detail
  13. {
  14. namespace thread
  15. {
  16. typedef void(*cleanup_func_t)(void*);
  17. typedef void(*cleanup_caller_t)(cleanup_func_t, void*);
  18. }
  19. BOOST_THREAD_DECL void set_tss_data(void const* key,detail::thread::cleanup_caller_t caller,detail::thread::cleanup_func_t func,void* tss_data,bool cleanup_existing);
  20. BOOST_THREAD_DECL void* get_tss_data(void const* key);
  21. }
  22. template <typename T>
  23. class thread_specific_ptr
  24. {
  25. private:
  26. thread_specific_ptr(thread_specific_ptr&);
  27. thread_specific_ptr& operator=(thread_specific_ptr&);
  28. typedef void(*original_cleanup_func_t)(T*);
  29. static void default_deleter(T* data)
  30. {
  31. delete data;
  32. }
  33. static void cleanup_caller(detail::thread::cleanup_func_t cleanup_function,void* data)
  34. {
  35. reinterpret_cast<original_cleanup_func_t>(cleanup_function)(static_cast<T*>(data));
  36. }
  37. detail::thread::cleanup_func_t cleanup;
  38. public:
  39. typedef T element_type;
  40. thread_specific_ptr():
  41. cleanup(reinterpret_cast<detail::thread::cleanup_func_t>(&default_deleter))
  42. {}
  43. explicit thread_specific_ptr(void (*func_)(T*))
  44. : cleanup(reinterpret_cast<detail::thread::cleanup_func_t>(func_))
  45. {}
  46. ~thread_specific_ptr()
  47. {
  48. detail::set_tss_data(this,0,0,0,true);
  49. }
  50. T* get() const
  51. {
  52. return static_cast<T*>(detail::get_tss_data(this));
  53. }
  54. T* operator->() const
  55. {
  56. return get();
  57. }
  58. typename add_reference<T>::type operator*() const
  59. {
  60. return *get();
  61. }
  62. T* release()
  63. {
  64. T* const temp=get();
  65. detail::set_tss_data(this,0,0,0,false);
  66. return temp;
  67. }
  68. void reset(T* new_value=0)
  69. {
  70. T* const current_value=get();
  71. if(current_value!=new_value)
  72. {
  73. detail::set_tss_data(this,&cleanup_caller,cleanup,new_value,true);
  74. }
  75. }
  76. };
  77. }
  78. #include <boost/config/abi_suffix.hpp>
  79. #endif