test_thread_safe_map.cpp
Go to the documentation of this file.
1 
28 
29 #include <boost/thread/thread.hpp>
30 #include <boost/bind.hpp>
31 #include <gtest/gtest.h>
32 #include <string>
33 
35 {
36 public:
37  explicit TestMultiThread(int num_threads)
38  {
39  last_value = 1;
40  map_.insert("a", last_value);
41  map_.insert("b", 2);
42 
43  boost::thread_group tg;
44  tg.create_thread(boost::bind(&TestMultiThread::write, this));
45 
46  for (int i = 0; i < num_threads; ++i)
47  {
48  tg.create_thread(boost::bind(&TestMultiThread::read, this));
49  }
50 
51  boost::this_thread::sleep(boost::posix_time::seconds(2));
52  tg.join_all();
53  };
54 
56  {
57  };
58 
59  void write()
60  {
61  mut.lock();
62  ++last_value;
63  map_.update("a", last_value);
64  mut.unlock();
65  boost::this_thread::sleep(boost::posix_time::microseconds(1));
66  };
67 
68  void read()
69  {
70  mut.lock_shared();
71  int value = map_.find("a");
72  EXPECT_EQ(value, last_value);
73  mut.unlock_shared();
74 
75  value = map_.find("b");
76  // b should be constant
77  EXPECT_EQ(value, 2);
78 
79  boost::this_thread::sleep(boost::posix_time::microseconds(1));
80  };
81 
82 private:
85  boost::shared_mutex mut;
86 };
87 
88 TEST(ThreadSafeMapOneThread, initialization)
89 {
91 
92  map.insert("a", 1);
93  map.insert("b", 2);
94 
95  int value = map.find("a");
96  EXPECT_EQ(value, 1);
97 
98  value = map.find("b");
99  EXPECT_EQ(value, 2);
100 
101  EXPECT_EQ(map.keys().size(), 2);
102 
103  EXPECT_STREQ(std::string("a").c_str(), std::string(map.keys()[0]).c_str());
104  EXPECT_STREQ(std::string("b").c_str(), std::string(map.keys()[1]).c_str());
105 }
106 
107 TEST(ThreadSafeMapOneThread, update)
108 {
110 
111  map.insert("a", 1);
112  map.insert("b", 2);
113 
114  int value = map.find("a");
115  EXPECT_EQ(value, 1);
116 
117  value = map.find("b");
118  EXPECT_EQ(value, 2);
119 
120 
121  map.update("a", 3);
122  value = map.find("a");
123  EXPECT_EQ(value, 3);
124 
125  value = map.find("b");
126  EXPECT_EQ(value, 2);
127 }
128 
129 TEST(ThreadSafeMapMultiThreads, update)
130 {
131  TestMultiThread tmt(12);
132 }
133 
134 // Run all the tests that were declared with TEST()
135 int main(int argc, char **argv)
136 {
137  testing::InitGoogleTest(&argc, argv);
138  return RUN_ALL_TESTS();
139 }
140 
141 /* For the emacs weenies in the crowd.
142 Local Variables:
143  c-basic-offset: 2
144 End:
145 */
bool update(const std::string &first, const T &value)
boost::shared_mutex mut
We needed a threadsafe hash map, with the possibility of multiple readers accessing the map at the sa...
TestMultiThread(int num_threads)
int main(int argc, char **argv)
std::vector< std::string > keys()
T find(std::string first)
bool insert(const std::string &first, const T &value)
TEST(ThreadSafeMapOneThread, initialization)
threadsafe::Map< int > map_


sr_utilities
Author(s): Ugo Cupcic
autogenerated on Tue Oct 13 2020 03:55:49