ConcurrentSkipListTest.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. * Copyright 2011-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // @author: Xin Liu <xliux@fb.com>
  17. #include <folly/ConcurrentSkipList.h>
  18. #include <atomic>
  19. #include <memory>
  20. #include <set>
  21. #include <system_error>
  22. #include <thread>
  23. #include <vector>
  24. #include <glog/logging.h>
  25. #include <folly/Memory.h>
  26. #include <folly/String.h>
  27. #include <folly/container/Foreach.h>
  28. #include <folly/memory/Arena.h>
  29. #include <folly/portability/GFlags.h>
  30. #include <folly/portability/GTest.h>
  31. DEFINE_int32(num_threads, 12, "num concurrent threads to test");
  32. namespace {
  33. template <typename ParentAlloc>
  34. struct ParanoidArenaAlloc {
  35. explicit ParanoidArenaAlloc(ParentAlloc& arena) : arena_(arena) {}
  36. ParanoidArenaAlloc(ParanoidArenaAlloc const&) = delete;
  37. ParanoidArenaAlloc(ParanoidArenaAlloc&&) = delete;
  38. ParanoidArenaAlloc& operator=(ParanoidArenaAlloc const&) = delete;
  39. ParanoidArenaAlloc& operator=(ParanoidArenaAlloc&&) = delete;
  40. void* allocate(size_t size) {
  41. void* result = arena_.get().allocate(size);
  42. allocated_.insert(result);
  43. return result;
  44. }
  45. void deallocate(void* ptr, size_t n) {
  46. EXPECT_EQ(1, allocated_.erase(ptr));
  47. arena_.get().deallocate(ptr, n);
  48. }
  49. bool isEmpty() const {
  50. return allocated_.empty();
  51. }
  52. std::reference_wrapper<ParentAlloc> arena_;
  53. std::set<void*> allocated_;
  54. };
  55. } // namespace
  56. namespace folly {
  57. template <typename ParentAlloc>
  58. struct AllocatorHasTrivialDeallocate<ParanoidArenaAlloc<ParentAlloc>>
  59. : AllocatorHasTrivialDeallocate<ParentAlloc> {};
  60. } // namespace folly
  61. namespace {
  62. using namespace folly;
  63. using std::vector;
  64. typedef int ValueType;
  65. typedef detail::SkipListNode<ValueType> SkipListNodeType;
  66. typedef ConcurrentSkipList<ValueType> SkipListType;
  67. typedef SkipListType::Accessor SkipListAccessor;
  68. typedef vector<ValueType> VectorType;
  69. typedef std::set<ValueType> SetType;
  70. static const int kHeadHeight = 2;
  71. static const int kMaxValue = 5000;
  72. static void randomAdding(
  73. int size,
  74. SkipListAccessor skipList,
  75. SetType* verifier,
  76. int maxValue = kMaxValue) {
  77. for (int i = 0; i < size; ++i) {
  78. int32_t r = rand() % maxValue;
  79. verifier->insert(r);
  80. skipList.add(r);
  81. }
  82. }
  83. static void randomRemoval(
  84. int size,
  85. SkipListAccessor skipList,
  86. SetType* verifier,
  87. int maxValue = kMaxValue) {
  88. for (int i = 0; i < size; ++i) {
  89. int32_t r = rand() % maxValue;
  90. verifier->insert(r);
  91. skipList.remove(r);
  92. }
  93. }
  94. static void sumAllValues(SkipListAccessor skipList, int64_t* sum) {
  95. *sum = 0;
  96. FOR_EACH (it, skipList) { *sum += *it; }
  97. VLOG(20) << "sum = " << sum;
  98. }
  99. static void concurrentSkip(
  100. const vector<ValueType>* values,
  101. SkipListAccessor skipList) {
  102. int64_t sum = 0;
  103. SkipListAccessor::Skipper skipper(skipList);
  104. FOR_EACH (it, *values) {
  105. if (skipper.to(*it)) {
  106. sum += *it;
  107. }
  108. }
  109. VLOG(20) << "sum = " << sum;
  110. }
  111. bool verifyEqual(SkipListAccessor skipList, const SetType& verifier) {
  112. EXPECT_EQ(verifier.size(), skipList.size());
  113. FOR_EACH (it, verifier) {
  114. CHECK(skipList.contains(*it)) << *it;
  115. SkipListType::const_iterator iter = skipList.find(*it);
  116. CHECK(iter != skipList.end());
  117. EXPECT_EQ(*iter, *it);
  118. }
  119. EXPECT_TRUE(std::equal(verifier.begin(), verifier.end(), skipList.begin()));
  120. return true;
  121. }
  122. TEST(ConcurrentSkipList, SequentialAccess) {
  123. {
  124. LOG(INFO) << "nodetype size=" << sizeof(SkipListNodeType);
  125. auto skipList(SkipListType::create(kHeadHeight));
  126. EXPECT_TRUE(skipList.first() == nullptr);
  127. EXPECT_TRUE(skipList.last() == nullptr);
  128. skipList.add(3);
  129. EXPECT_TRUE(skipList.contains(3));
  130. EXPECT_FALSE(skipList.contains(2));
  131. EXPECT_EQ(3, *skipList.first());
  132. EXPECT_EQ(3, *skipList.last());
  133. EXPECT_EQ(3, *skipList.find(3));
  134. EXPECT_FALSE(skipList.find(3) == skipList.end());
  135. EXPECT_TRUE(skipList.find(2) == skipList.end());
  136. {
  137. SkipListAccessor::Skipper skipper(skipList);
  138. skipper.to(3);
  139. CHECK_EQ(3, *skipper);
  140. }
  141. skipList.add(2);
  142. EXPECT_EQ(2, *skipList.first());
  143. EXPECT_EQ(3, *skipList.last());
  144. skipList.add(5);
  145. EXPECT_EQ(5, *skipList.last());
  146. skipList.add(3);
  147. EXPECT_EQ(5, *skipList.last());
  148. auto ret = skipList.insert(9);
  149. EXPECT_EQ(9, *ret.first);
  150. EXPECT_TRUE(ret.second);
  151. ret = skipList.insert(5);
  152. EXPECT_EQ(5, *ret.first);
  153. EXPECT_FALSE(ret.second);
  154. EXPECT_EQ(2, *skipList.first());
  155. EXPECT_EQ(9, *skipList.last());
  156. EXPECT_TRUE(skipList.pop_back());
  157. EXPECT_EQ(5, *skipList.last());
  158. EXPECT_TRUE(skipList.pop_back());
  159. EXPECT_EQ(3, *skipList.last());
  160. skipList.add(9);
  161. skipList.add(5);
  162. CHECK(skipList.contains(2));
  163. CHECK(skipList.contains(3));
  164. CHECK(skipList.contains(5));
  165. CHECK(skipList.contains(9));
  166. CHECK(!skipList.contains(4));
  167. // lower_bound
  168. auto it = skipList.lower_bound(5);
  169. EXPECT_EQ(5, *it);
  170. it = skipList.lower_bound(4);
  171. EXPECT_EQ(5, *it);
  172. it = skipList.lower_bound(9);
  173. EXPECT_EQ(9, *it);
  174. it = skipList.lower_bound(12);
  175. EXPECT_FALSE(it.good());
  176. it = skipList.begin();
  177. EXPECT_EQ(2, *it);
  178. // skipper test
  179. SkipListAccessor::Skipper skipper(skipList);
  180. skipper.to(3);
  181. EXPECT_EQ(3, skipper.data());
  182. skipper.to(5);
  183. EXPECT_EQ(5, skipper.data());
  184. CHECK(!skipper.to(7));
  185. skipList.remove(5);
  186. skipList.remove(3);
  187. CHECK(skipper.to(9));
  188. EXPECT_EQ(9, skipper.data());
  189. CHECK(!skipList.contains(3));
  190. skipList.add(3);
  191. CHECK(skipList.contains(3));
  192. int pos = 0;
  193. for (auto entry : skipList) {
  194. LOG(INFO) << "pos= " << pos++ << " value= " << entry;
  195. }
  196. }
  197. {
  198. auto skipList(SkipListType::create(kHeadHeight));
  199. SetType verifier;
  200. randomAdding(10000, skipList, &verifier);
  201. verifyEqual(skipList, verifier);
  202. // test skipper
  203. SkipListAccessor::Skipper skipper(skipList);
  204. int num_skips = 1000;
  205. for (int i = 0; i < num_skips; ++i) {
  206. int n = i * kMaxValue / num_skips;
  207. bool found = skipper.to(n);
  208. EXPECT_EQ(found, (verifier.find(n) != verifier.end()));
  209. }
  210. }
  211. }
  212. static std::string makeRandomeString(int len) {
  213. std::string s;
  214. for (int j = 0; j < len; j++) {
  215. s.push_back((rand() % 26) + 'A');
  216. }
  217. return s;
  218. }
  219. TEST(ConcurrentSkipList, TestStringType) {
  220. typedef folly::ConcurrentSkipList<std::string> SkipListT;
  221. std::shared_ptr<SkipListT> skip = SkipListT::createInstance();
  222. SkipListT::Accessor accessor(skip);
  223. {
  224. for (int i = 0; i < 100000; i++) {
  225. std::string s = makeRandomeString(7);
  226. accessor.insert(s);
  227. }
  228. }
  229. EXPECT_TRUE(std::is_sorted(accessor.begin(), accessor.end()));
  230. }
  231. struct UniquePtrComp {
  232. bool operator()(const std::unique_ptr<int>& x, const std::unique_ptr<int>& y)
  233. const {
  234. if (!x) {
  235. return false;
  236. }
  237. if (!y) {
  238. return true;
  239. }
  240. return *x < *y;
  241. }
  242. };
  243. TEST(ConcurrentSkipList, TestMovableData) {
  244. typedef folly::ConcurrentSkipList<std::unique_ptr<int>, UniquePtrComp>
  245. SkipListT;
  246. auto sl = SkipListT::createInstance();
  247. SkipListT::Accessor accessor(sl);
  248. static const int N = 10;
  249. for (int i = 0; i < N; ++i) {
  250. accessor.insert(std::make_unique<int>(i));
  251. }
  252. for (int i = 0; i < N; ++i) {
  253. EXPECT_TRUE(
  254. accessor.find(std::unique_ptr<int>(new int(i))) != accessor.end());
  255. }
  256. EXPECT_TRUE(
  257. accessor.find(std::unique_ptr<int>(new int(N))) == accessor.end());
  258. }
  259. void testConcurrentAdd(int numThreads) {
  260. auto skipList(SkipListType::create(kHeadHeight));
  261. vector<std::thread> threads;
  262. vector<SetType> verifiers(numThreads);
  263. try {
  264. for (int i = 0; i < numThreads; ++i) {
  265. threads.push_back(
  266. std::thread(&randomAdding, 100, skipList, &verifiers[i], kMaxValue));
  267. }
  268. } catch (const std::system_error& e) {
  269. LOG(WARNING) << "Caught " << exceptionStr(e) << ": could only create "
  270. << threads.size() << " threads out of " << numThreads;
  271. }
  272. for (size_t i = 0; i < threads.size(); ++i) {
  273. threads[i].join();
  274. }
  275. SetType all;
  276. FOR_EACH (s, verifiers) { all.insert(s->begin(), s->end()); }
  277. verifyEqual(skipList, all);
  278. }
  279. TEST(ConcurrentSkipList, ConcurrentAdd) {
  280. // test it many times
  281. for (int numThreads = 10; numThreads < 10000; numThreads += 1000) {
  282. testConcurrentAdd(numThreads);
  283. }
  284. }
  285. void testConcurrentRemoval(int numThreads, int maxValue) {
  286. auto skipList = SkipListType::create(kHeadHeight);
  287. for (int i = 0; i < maxValue; ++i) {
  288. skipList.add(i);
  289. }
  290. vector<std::thread> threads;
  291. vector<SetType> verifiers(numThreads);
  292. try {
  293. for (int i = 0; i < numThreads; ++i) {
  294. threads.push_back(
  295. std::thread(&randomRemoval, 100, skipList, &verifiers[i], maxValue));
  296. }
  297. } catch (const std::system_error& e) {
  298. LOG(WARNING) << "Caught " << exceptionStr(e) << ": could only create "
  299. << threads.size() << " threads out of " << numThreads;
  300. }
  301. FOR_EACH (t, threads) { (*t).join(); }
  302. SetType all;
  303. FOR_EACH (s, verifiers) { all.insert(s->begin(), s->end()); }
  304. CHECK_EQ(maxValue, all.size() + skipList.size());
  305. for (int i = 0; i < maxValue; ++i) {
  306. if (all.find(i) != all.end()) {
  307. CHECK(!skipList.contains(i)) << i;
  308. } else {
  309. CHECK(skipList.contains(i)) << i;
  310. }
  311. }
  312. }
  313. TEST(ConcurrentSkipList, ConcurrentRemove) {
  314. for (int numThreads = 10; numThreads < 1000; numThreads += 100) {
  315. testConcurrentRemoval(numThreads, 100 * numThreads);
  316. }
  317. }
  318. static void
  319. testConcurrentAccess(int numInsertions, int numDeletions, int maxValue) {
  320. auto skipList = SkipListType::create(kHeadHeight);
  321. vector<SetType> verifiers(FLAGS_num_threads);
  322. vector<int64_t> sums(FLAGS_num_threads);
  323. vector<vector<ValueType>> skipValues(FLAGS_num_threads);
  324. for (int i = 0; i < FLAGS_num_threads; ++i) {
  325. for (int j = 0; j < numInsertions; ++j) {
  326. skipValues[i].push_back(rand() % (maxValue + 1));
  327. }
  328. std::sort(skipValues[i].begin(), skipValues[i].end());
  329. }
  330. vector<std::thread> threads;
  331. for (int i = 0; i < FLAGS_num_threads; ++i) {
  332. switch (i % 8) {
  333. case 0:
  334. case 1:
  335. threads.push_back(std::thread(
  336. randomAdding, numInsertions, skipList, &verifiers[i], maxValue));
  337. break;
  338. case 2:
  339. threads.push_back(std::thread(
  340. randomRemoval, numDeletions, skipList, &verifiers[i], maxValue));
  341. break;
  342. case 3:
  343. threads.push_back(
  344. std::thread(concurrentSkip, &skipValues[i], skipList));
  345. break;
  346. default:
  347. threads.push_back(std::thread(sumAllValues, skipList, &sums[i]));
  348. break;
  349. }
  350. }
  351. FOR_EACH (t, threads) { (*t).join(); }
  352. // just run through it, no need to verify the correctness.
  353. }
  354. TEST(ConcurrentSkipList, ConcurrentAccess) {
  355. testConcurrentAccess(10000, 100, kMaxValue);
  356. testConcurrentAccess(100000, 10000, kMaxValue * 10);
  357. testConcurrentAccess(1000000, 100000, kMaxValue);
  358. }
  359. struct NonTrivialValue {
  360. static std::atomic<int> InstanceCounter;
  361. static const int kBadPayLoad;
  362. NonTrivialValue() : payload_(kBadPayLoad) {
  363. ++InstanceCounter;
  364. }
  365. explicit NonTrivialValue(int payload) : payload_(payload) {
  366. ++InstanceCounter;
  367. }
  368. NonTrivialValue(const NonTrivialValue& rhs) : payload_(rhs.payload_) {
  369. ++InstanceCounter;
  370. }
  371. NonTrivialValue& operator=(const NonTrivialValue& rhs) {
  372. payload_ = rhs.payload_;
  373. return *this;
  374. }
  375. ~NonTrivialValue() {
  376. --InstanceCounter;
  377. }
  378. bool operator<(const NonTrivialValue& rhs) const {
  379. EXPECT_NE(kBadPayLoad, payload_);
  380. EXPECT_NE(kBadPayLoad, rhs.payload_);
  381. return payload_ < rhs.payload_;
  382. }
  383. private:
  384. int payload_;
  385. };
  386. std::atomic<int> NonTrivialValue::InstanceCounter(0);
  387. const int NonTrivialValue::kBadPayLoad = 0xDEADBEEF;
  388. template <typename SkipListPtrType>
  389. void TestNonTrivialDeallocation(SkipListPtrType& list) {
  390. {
  391. auto accessor = typename SkipListPtrType::element_type::Accessor(list);
  392. static const size_t N = 10000;
  393. for (size_t i = 0; i < N; ++i) {
  394. accessor.add(NonTrivialValue(i));
  395. }
  396. list.reset();
  397. }
  398. EXPECT_EQ(0, NonTrivialValue::InstanceCounter);
  399. }
  400. template <typename ParentAlloc>
  401. void NonTrivialDeallocationWithParanoid(ParentAlloc& parentAlloc) {
  402. using ParanoidAlloc = ParanoidArenaAlloc<ParentAlloc>;
  403. using Alloc = CxxAllocatorAdaptor<void, ParanoidAlloc>;
  404. using ParanoidSkipListType =
  405. ConcurrentSkipList<NonTrivialValue, std::less<NonTrivialValue>, Alloc>;
  406. ParanoidAlloc paranoidAlloc(parentAlloc);
  407. Alloc alloc(paranoidAlloc);
  408. auto list = ParanoidSkipListType::createInstance(10, alloc);
  409. TestNonTrivialDeallocation(list);
  410. EXPECT_TRUE(paranoidAlloc.isEmpty());
  411. }
  412. TEST(ConcurrentSkipList, NonTrivialDeallocationWithParanoidSysAlloc) {
  413. SysAllocator<void> alloc;
  414. NonTrivialDeallocationWithParanoid(alloc);
  415. }
  416. TEST(ConcurrentSkipList, NonTrivialDeallocationWithParanoidSysArena) {
  417. SysArena arena;
  418. SysArenaAllocator<void> alloc(arena);
  419. NonTrivialDeallocationWithParanoid(alloc);
  420. }
  421. TEST(ConcurrentSkipList, NonTrivialDeallocationWithSysArena) {
  422. using SysArenaSkipListType = ConcurrentSkipList<
  423. NonTrivialValue,
  424. std::less<NonTrivialValue>,
  425. SysArenaAllocator<void>>;
  426. SysArena arena;
  427. SysArenaAllocator<void> alloc(arena);
  428. auto list = SysArenaSkipListType::createInstance(10, alloc);
  429. TestNonTrivialDeallocation(list);
  430. }
  431. } // namespace
  432. int main(int argc, char* argv[]) {
  433. testing::InitGoogleTest(&argc, argv);
  434. google::InitGoogleLogging(argv[0]);
  435. gflags::ParseCommandLineFlags(&argc, &argv, true);
  436. return RUN_ALL_TESTS();
  437. }