-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_test.cpp
More file actions
85 lines (69 loc) · 1.75 KB
/
memory_test.cpp
File metadata and controls
85 lines (69 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <thread>
#include <string>
#include <chrono>
#include <gtest/gtest.h>
#include <allocator.h>
/**
* @brief 测试用例
*/
class TestCase
{
public:
std::string name;
std::thread::id id;
std::chrono::time_point<std::chrono::system_clock> time;
public:
TestCase()
: TestCase("test")
{
}
explicit TestCase(const std::string & name)
: name(name)
, id(std::this_thread::get_id())
, time(std::chrono::system_clock::now())
{
}
};
class MemoryTest : public testing::Test
{
public:
allocator<TestCase> alloc;
};
TEST_F(MemoryTest, SingleThreadMemoryTest)
{
TestCase * p = alloc.allocate(1);
EXPECT_NE(p, nullptr);
alloc.construct(p);
EXPECT_EQ(p->name, "test");
EXPECT_EQ(p->id, std::this_thread::get_id());
alloc.destroy(p);
alloc.deallocate(p, 1);
}
TEST_F(MemoryTest, MultiThreadMemoryTest)
{
constexpr int THREAD_NUM = 4;
std::vector<std::thread> threads;
for (int i = 0; i < THREAD_NUM; ++i) {
threads.emplace_back([]() {
// 当前线程的分配器
allocator<TestCase> alloc;
std::vector<TestCase *> cases;
constexpr int size = 1000;
cases.reserve(size);
for (int j = 0; j < size; ++j) {
TestCase * p = alloc.allocate(1);
alloc.construct(p);
EXPECT_EQ(p->name, "test");
EXPECT_EQ(p->id, std::this_thread::get_id());
cases.emplace_back(p);
}
for (int j = 0; j < size; ++j) {
alloc.destroy(cases[j]);
alloc.deallocate(cases[j], 1);
}
});
}
for (int i = 0; i < THREAD_NUM; ++i) {
threads[i].join();
}
}