-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadCache.cpp
More file actions
74 lines (63 loc) · 2.11 KB
/
ThreadCache.cpp
File metadata and controls
74 lines (63 loc) · 2.11 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
//
// Created by ASUS on 2026/3/21.
//
#include "ThreadCache.h"
#include"CentralCache.h"
thread_local ThreadCache* pTLSThreadCache = nullptr;
void *ThreadCache::allocate(size_t size) {
assert(size<MAX_BYTE);
size_t pad_size=SizeClass::Roundup(size);
size_t index=SizeClass::index(pad_size);
if (freelist_[index].empty()) {
return FetchFromCentralCache(index,pad_size);
}
void* ptr=freelist_[index].pop();
if (ptr==nullptr) {
return nullptr;
}
else {
return ptr;
}
}
void ThreadCache::deallocate(void *ptr, size_t size) {
assert(size < MAX_BYTE && ptr != nullptr);
size_t pad_size = SizeClass::Roundup(size);
size_t index = SizeClass::index(pad_size);
Freelist& list = freelist_[index];
list.push(ptr);
// freelist 过长时,回收一批对象给 CentralCache
if (list.Size() >= list.MaxSize()) {
ListTooLong(list, pad_size);
}
}
void* ThreadCache::FetchFromCentralCache(size_t index, size_t alignSize) {
#ifdef _WIN32
size_t batchNum = std::min(freelist_[index].MaxSize(), SizeClass::NumMoveSize(alignSize));
#else
size_t batchNum = std::min(freelist_[index].MaxSize(), SizeClass::NumMoveSize(alignSize));
#endif
if (batchNum == freelist_[index].MaxSize()) {
freelist_[index].MaxSize()++;
}
void* start = nullptr;
void* end = nullptr;
size_t actualNum = CentralCache::GetInstance()->FetchRangeObj(start, end, alignSize, batchNum);
assert(actualNum >= 1);
if (actualNum == 1) {
assert(start == end);
return start;
} else {
// 把第一个返回给用户,剩下的挂到 freelist
void* next = *reinterpret_cast<void**>(start);
freelist_[index].PushRange(next, end, actualNum - 1);
// 断开返回对象和后面链表的关系,避免误串
*reinterpret_cast<void**>(start) = nullptr;
return start;
}
}
void ThreadCache::ListTooLong(Freelist &list, size_t size) {
void* start=nullptr;
void* end=nullptr;
list.PopRange(start,end,list.MaxSize());
CentralCache::GetInstance()->ReleaseListToSpans(start,size);
}