-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectPoolStudy.h
More file actions
100 lines (97 loc) · 2.55 KB
/
Copy pathObjectPoolStudy.h
File metadata and controls
100 lines (97 loc) · 2.55 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#pragma once
#include <vector>
#include <memory>
#include <mutex>
#include <thread>
#include <sstream>
#include <atomic>
#include <iostream>
using namespace std;
namespace TestObjectPool {
class Data {
public:
int i;
Data()
{
i = 0;
cout << " created " << endl;
}
~Data()
{
cout << " destroyed " << endl;
}
};
template<class T>
class SimpleObjectPool2
{
private:
typedef std::pair<shared_ptr<T>, bool> elemUnit;
vector<elemUnit> objects;
int size;
public:
SimpleObjectPool2(int length = 10)
{
size = length;
}
shared_ptr<T> GetElem()
{
for (elemUnit& ele : objects)
{
if (ele.second == true)
{
ele.second = false;
return ele.first;
}
}
if (size > objects.size())
{
shared_ptr<T> elePtr = make_shared<T>();
objects.emplace_back(make_pair(std::move(elePtr), false));
return objects.back().first;
}
else
{
cout << "对象池已满" << endl;
return nullptr;
}
}
void GC()
{
for (int i = 0; i < objects.size(); i++)
{
if (objects[i].second == false)
{
//如果被使用了,则检查是否实际已经没有其他人使用,没有人使用的话,就得及时回收或者根据某种策略销毁
if (objects[i].first.unique())
{
//没其他人使用了
objects[i].second = true;
cout << "回收了【" << i << "】对象" << endl;
//主动调用析构函数并不会真的销毁对象内存,可以作为一种回收方式
//objectpool[i].first->~Data();
//假设触发了某种销毁策略
//objects[i].first = nullptr;
}
}
}
}
};
void testObject2()
{
SimpleObjectPool2<Data> pool;
int testCount = 100;
while (testCount > 0)
{
auto ele = pool.GetElem();
if (ele != nullptr)
cout << ele->i << endl;
else
{
cout << "xxx" << endl;
}
testCount--;
if (testCount % 10 == 9)
pool.GC();
}
}
}