test_helpers.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Copyright (C) 2011 Tim Blechmann
  2. //
  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. #ifndef BOOST_LOCKFREE_TEST_HELPERS
  7. #define BOOST_LOCKFREE_TEST_HELPERS
  8. #include <set>
  9. #include <boost/array.hpp>
  10. #include <boost/lockfree/detail/atomic.hpp>
  11. #include <boost/thread.hpp>
  12. #include <boost/cstdint.hpp>
  13. template <typename int_type>
  14. int_type generate_id(void)
  15. {
  16. static boost::lockfree::detail::atomic<int_type> generator(0);
  17. return ++generator;
  18. }
  19. template <typename int_type, size_t buckets>
  20. class static_hashed_set
  21. {
  22. public:
  23. int calc_index(int_type id)
  24. {
  25. // knuth hash ... does not need to be good, but has to be portable
  26. size_t factor = size_t((float)buckets * 1.616f);
  27. return ((size_t)id * factor) % buckets;
  28. }
  29. bool insert(int_type const & id)
  30. {
  31. std::size_t index = calc_index(id);
  32. boost::lock_guard<boost::mutex> lock (ref_mutex[index]);
  33. std::pair<typename std::set<int_type>::iterator, bool> p;
  34. p = data[index].insert(id);
  35. return p.second;
  36. }
  37. bool find (int_type const & id)
  38. {
  39. std::size_t index = calc_index(id);
  40. boost::lock_guard<boost::mutex> lock (ref_mutex[index]);
  41. return data[index].find(id) != data[index].end();
  42. }
  43. bool erase(int_type const & id)
  44. {
  45. std::size_t index = calc_index(id);
  46. boost::lock_guard<boost::mutex> lock (ref_mutex[index]);
  47. if (data[index].find(id) != data[index].end()) {
  48. data[index].erase(id);
  49. assert(data[index].find(id) == data[index].end());
  50. return true;
  51. }
  52. else
  53. return false;
  54. }
  55. std::size_t count_nodes(void) const
  56. {
  57. std::size_t ret = 0;
  58. for (int i = 0; i != buckets; ++i) {
  59. boost::lock_guard<boost::mutex> lock (ref_mutex[i]);
  60. ret += data[i].size();
  61. }
  62. return ret;
  63. }
  64. private:
  65. boost::array<std::set<int_type>, buckets> data;
  66. mutable boost::array<boost::mutex, buckets> ref_mutex;
  67. };
  68. struct test_equal
  69. {
  70. test_equal(int i):
  71. i(i)
  72. {}
  73. void operator()(int arg) const
  74. {
  75. BOOST_REQUIRE_EQUAL(arg, i);
  76. }
  77. int i;
  78. };
  79. struct dummy_functor
  80. {
  81. void operator()(int /* arg */) const
  82. {
  83. }
  84. };
  85. #endif