libcopp  1.1.0
id_allocator_test.cpp
Go to the documentation of this file.
1 #include <cstdio>
2 #include <cstring>
3 #include <ctime>
4 #include <iostream>
5 #include <set>
6 
7 
8 #include "frame/test_macros.h"
10 
11 
12 #if ((defined(__cplusplus) && __cplusplus >= 201103L) || (defined(_MSC_VER) && _MSC_VER >= 1800)) && \
13  defined(UTIL_CONFIG_COMPILER_CXX_LAMBDAS) && UTIL_CONFIG_COMPILER_CXX_LAMBDAS
14 
15 #include <memory>
16 #include <thread>
17 
18 #endif
19 
20 CASE_TEST(coroutine_task, id_allocator_16) {
22 
23  time_t begin_time = time(NULL);
24 
25  size_t id_num = 3 * (1 << 8) + 100; // sleep 2-3 times
26  std::set<uint16_t> s;
27 
28  for (size_t i = 0; i < id_num; ++i) {
29  uint16_t id = alloc.allocate();
30  CASE_EXPECT_TRUE(s.find(id) == s.end());
31  s.insert(id);
32  }
33 
34  time_t end_time = time(NULL);
35  CASE_EXPECT_EQ(id_num, s.size());
36  CASE_EXPECT_GE(end_time - begin_time, (time_t)2);
37 }
38 
39 CASE_TEST(coroutine_task, id_allocator_32) {
41 
42  time_t begin_time = time(NULL);
43 
44  size_t id_num = 3 * (1 << 16) + 100; // sleep 2-3 times
45  std::set<uint32_t> s;
46 
47  for (size_t i = 0; i < id_num; ++i) {
48  uint32_t id = alloc.allocate();
49  CASE_EXPECT_TRUE(s.find(id) == s.end());
50  s.insert(id);
51  }
52 
53  time_t end_time = time(NULL);
54  CASE_EXPECT_EQ(id_num, s.size());
55  CASE_EXPECT_GE(end_time - begin_time, (time_t)2);
56 }
57 
58 
59 #if ((defined(__cplusplus) && __cplusplus >= 201103L) || (defined(_MSC_VER) && _MSC_VER >= 1800)) && \
60  defined(UTIL_CONFIG_COMPILER_CXX_LAMBDAS) && UTIL_CONFIG_COMPILER_CXX_LAMBDAS
61 
62 CASE_TEST(coroutine_task, id_allocator_mt) {
64 
65  time_t begin_time = time(NULL);
66  std::unique_ptr<std::thread> thds[4];
67  std::set<uint32_t> s[4];
68  for (int i = 0; i < 4; ++i) {
69  std::set<uint32_t> *sp = &s[i];
70  thds[i].reset(new std::thread([sp, &alloc]() {
71  size_t id_num = 36768;
72 
73  for (size_t i = 0; i < id_num; ++i) {
74  uint32_t id = alloc.allocate();
75  CASE_EXPECT_TRUE(sp->find(id) == sp->end());
76  sp->insert(id);
77  }
78  }));
79  }
80 
81  size_t id_num = 0;
82  for (int i = 0; i < 4; ++i) {
83  thds[i]->join();
84  id_num += 36768;
85 
86  if (i != 0) {
87  s[0].insert(s[i].begin(), s[i].end());
88  }
89  }
90 
91  time_t end_time = time(NULL);
92  CASE_EXPECT_EQ(id_num, s[0].size());
93  CASE_EXPECT_GE(end_time - begin_time, (time_t)1);
94 }
95 
96 #endif
value_type allocate() UTIL_CONFIG_NOEXCEPT
#define CASE_EXPECT_EQ(l, r)
Definition: test_macros.h:62
#define CASE_EXPECT_TRUE(c)
Definition: test_macros.h:60
#define CASE_EXPECT_GE(l, r)
Definition: test_macros.h:67
CASE_TEST(coroutine_task, id_allocator_16)