Advertisement
Guest User

pachanga

a guest
Feb 20th, 2009
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. SUITE(ConcurrentHashMapTest)
  2. {
  3. struct Foo
  4. {
  5. Foo(int i) : dummy(i) {}
  6. int dummy;
  7. };
  8. typedef boost::shared_ptr<Foo> FooPtr;
  9.  
  10. template<class T>
  11. struct shared_ptr_hash_compare
  12. {
  13. static size_t hash(const boost::shared_ptr<T>& ptr)
  14. {
  15. return (size_t)ptr.get();
  16. }
  17. static bool equal(const boost::shared_ptr<T>& a, const boost::shared_ptr<T>& b)
  18. {
  19. return a == b;
  20. }
  21. };
  22.  
  23. typedef tbb::concurrent_hash_map<FooPtr, FooPtr, shared_ptr_hash_compare<Foo> > Map;
  24.  
  25. struct Accessor
  26. {
  27. Accessor(Map& m) : map(m) {}
  28.  
  29. void run()
  30. {
  31. while(map.size() > 0)
  32. {
  33. BOOST_FOREACH(Map::value_type& el, map)
  34. {
  35. boost::this_thread::yield();
  36. el.second->dummy += 1;
  37. }
  38. }
  39. }
  40.  
  41. Map& map;
  42. };
  43.  
  44. struct Deleter
  45. {
  46. Deleter(Map& m) : map(m) {}
  47.  
  48. void run()
  49. {
  50. while(map.size() > 0)
  51. {
  52. Map::iterator it = map.begin();
  53. if(it != map.end())
  54. map.erase(it->first);
  55.  
  56. boost::this_thread::yield();
  57. }
  58. }
  59.  
  60. Map& map;
  61. };
  62.  
  63. TEST(ConcurrentAccessToSharedPtrs)
  64. {
  65. Map map;
  66.  
  67. for(size_t i=0; i<10000; ++i)
  68. {
  69. FooPtr foo(new Foo(i));
  70. map.insert(std::make_pair(foo, foo));
  71. }
  72.  
  73. Accessor accessor(map);
  74. Deleter deleter(map);
  75.  
  76. boost::thread_group thg;
  77. thg.create_thread(boost::bind(&Accessor::run, boost::ref(accessor)));
  78. thg.create_thread(boost::bind(&Deleter::run, boost::ref(deleter)));
  79.  
  80. thg.join_all();
  81. }
  82. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement