thread_info_base.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // detail/thread_info_base.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2013 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_THREAD_INFO_BASE_HPP
  11. #define BOOST_ASIO_DETAIL_THREAD_INFO_BASE_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <climits>
  16. #include <cstddef>
  17. #include <boost/asio/detail/noncopyable.hpp>
  18. #include <boost/asio/detail/push_options.hpp>
  19. namespace boost {
  20. namespace asio {
  21. namespace detail {
  22. class thread_info_base
  23. : private noncopyable
  24. {
  25. public:
  26. thread_info_base()
  27. : reusable_memory_(0)
  28. {
  29. }
  30. ~thread_info_base()
  31. {
  32. if (reusable_memory_)
  33. ::operator delete(reusable_memory_);
  34. }
  35. static void* allocate(thread_info_base* this_thread, std::size_t size)
  36. {
  37. if (this_thread && this_thread->reusable_memory_)
  38. {
  39. void* const pointer = this_thread->reusable_memory_;
  40. this_thread->reusable_memory_ = 0;
  41. unsigned char* const mem = static_cast<unsigned char*>(pointer);
  42. if (static_cast<std::size_t>(mem[0]) >= size)
  43. {
  44. mem[size] = mem[0];
  45. return pointer;
  46. }
  47. ::operator delete(pointer);
  48. }
  49. void* const pointer = ::operator new(size + 1);
  50. unsigned char* const mem = static_cast<unsigned char*>(pointer);
  51. mem[size] = (size <= UCHAR_MAX) ? static_cast<unsigned char>(size) : 0;
  52. return pointer;
  53. }
  54. static void deallocate(thread_info_base* this_thread,
  55. void* pointer, std::size_t size)
  56. {
  57. if (size <= UCHAR_MAX)
  58. {
  59. if (this_thread && this_thread->reusable_memory_ == 0)
  60. {
  61. unsigned char* const mem = static_cast<unsigned char*>(pointer);
  62. mem[0] = mem[size];
  63. this_thread->reusable_memory_ = pointer;
  64. return;
  65. }
  66. }
  67. ::operator delete(pointer);
  68. }
  69. private:
  70. void* reusable_memory_;
  71. };
  72. } // namespace detail
  73. } // namespace asio
  74. } // namespace boost
  75. #include <boost/asio/detail/pop_options.hpp>
  76. #endif // BOOST_ASIO_DETAIL_THREAD_INFO_BASE_HPP