$search
00001 00027 #include "sr_utilities/thread_safe_map.hpp" 00028 00029 #include <boost/thread/thread.hpp> 00030 #include <boost/bind.hpp> 00031 #include <gtest/gtest.h> 00032 #include <string> 00033 00034 class TestMultiThread 00035 { 00036 public: 00037 TestMultiThread(int num_threads) 00038 { 00039 last_value = 1; 00040 map_.insert("a", last_value); 00041 map_.insert("b", 2); 00042 00043 boost::thread_group tg; 00044 tg.create_thread(boost::bind(&TestMultiThread::write, this)); 00045 00046 for(int i=0; i<num_threads; ++i) 00047 tg.create_thread(boost::bind(&TestMultiThread::read, this )); 00048 00049 boost::this_thread::sleep(boost::posix_time::seconds(2)); 00050 tg.join_all(); 00051 }; 00052 00053 ~TestMultiThread() 00054 {}; 00055 00056 void write() 00057 { 00058 mut.lock(); 00059 ++last_value; 00060 map_.update("a", last_value); 00061 mut.unlock(); 00062 boost::this_thread::sleep(boost::posix_time::microseconds(1)); 00063 }; 00064 00065 void read() 00066 { 00067 mut.lock_shared(); 00068 int value = map_.find("a"); 00069 EXPECT_EQ(value, last_value); 00070 mut.unlock_shared(); 00071 00072 value = map_.find("b"); 00073 //b should be constant 00074 EXPECT_EQ(value, 2); 00075 00076 boost::this_thread::sleep(boost::posix_time::microseconds(1)); 00077 }; 00078 00079 private: 00080 threadsafe::Map<int> map_; 00081 int last_value; 00082 boost::shared_mutex mut; 00083 }; 00084 00085 TEST(ThreadSafeMapOneThread, initialization) 00086 { 00087 threadsafe::Map<int> map; 00088 00089 map.insert("a", 1); 00090 map.insert("b", 2); 00091 00092 int value = map.find("a"); 00093 EXPECT_EQ(value, 1); 00094 00095 value = map.find("b"); 00096 EXPECT_EQ(value, 2); 00097 00098 EXPECT_EQ(map.keys().size(), 2); 00099 00100 EXPECT_EQ(map.keys()[0].compare("a"), 0 ); 00101 EXPECT_EQ(map.keys()[1].compare("b"), 0 ); 00102 } 00103 00104 TEST(ThreadSafeMapOneThread, update) 00105 { 00106 threadsafe::Map<int> map; 00107 00108 map.insert("a", 1); 00109 map.insert("b", 2); 00110 00111 int value = map.find("a"); 00112 EXPECT_EQ(value, 1); 00113 00114 value = map.find("b"); 00115 EXPECT_EQ(value, 2); 00116 00117 00118 map.update("a", 3); 00119 value = map.find("a"); 00120 EXPECT_EQ(value, 3); 00121 00122 value = map.find("b"); 00123 EXPECT_EQ(value, 2); 00124 } 00125 00126 TEST(ThreadSafeMapMultiThreads, update) 00127 { 00128 TestMultiThread tmt(12); 00129 } 00130 00131 // Run all the tests that were declared with TEST() 00132 int main(int argc, char **argv) 00133 { 00134 testing::InitGoogleTest(&argc, argv); 00135 return RUN_ALL_TESTS(); 00136 } 00137 00138 /* For the emacs weenies in the crowd. 00139 Local Variables: 00140 c-basic-offset: 2 00141 End: 00142 */