#pragma once #include "Common.h" #include "ThreadCache.h" #include "PageCache.h" #include "ObjectPool.h" static void* ConcurrentAlloc(size_t size) { if (size > MAX_BYTES) { size_t alignSize = SizeClass::RoundUp(size); size_t kpage = alignSize >> PAGE_SHIFT; PageCache::GetInstance()->_pageMtx.lock(); Span* span = PageCache::GetInstance()->NewSpan(kpage); span->_objSize = size; PageCache::GetInstance()->_pageMtx.unlock(); void* ptr = (void*)(span->_pageId << PAGE_SHIFT); return ptr; } else { // 通过TLS 每个线程无锁的获取自己的专属的ThreadCache对象 if (pTLSThreadCache == nullptr) { static ObjectPool<ThreadCache> tcPool; //pTLSThreadCache = new ThreadCache; pTLSThreadCache = tcPool.New(); } //cout << std::this_thread::get_id() << ":" << pTLSThreadCache << endl; return pTLSThreadCache->Allocate(size); } } static void ConcurrentFree(void* ptr) { Span* span = PageCache::GetInstance()->MapObjectToSpan(ptr); size_t size = span->_objSize; if (size > MAX_BYTES) { PageCache::GetInstance()->_pageMtx.lock(); PageCache::GetInstance()->ReleaseSpanToPageCache(span); PageCache::GetInstance()->_pageMtx.unlock(); } else { assert(pTLSThreadCache); pTLSThreadCache->Deallocate(ptr, size); } }
时间: 2024-04-12 09:34:23 浏览: 214
这段代码实现了一个名为`ConcurrentAlloc`的静态函数,用于在多线程环境下分配内存。
函数首先检查请求的大小`size`是否超过了最大字节数`MAX_BYTES`。如果超过了最大字节数,它会按照一定的对齐方式计算出相应的页数,并从`PageCache`获取一个`Span`对象来分配内存。然后,它将计算得到的页地址转换为指针,并返回该指针作为分配的内存。
如果请求的大小没有超过最大字节数,它将通过线程本地存储(TLS)获取每个线程专属的`ThreadCache`对象。如果此对象为空,则使用对象池`tcPool`来分配一个新的`ThreadCache`对象,并将其赋值给`pTLSThreadCache`。然后,它调用`pTLSThreadCache->Allocate(size)`来从线程专属的缓存中分配内存,并返回分配的内存指针。
另外,代码还提供了一个名为`ConcurrentFree`的静态函数,用于在多线程环境下释放通过`ConcurrentAlloc`分配的内存。该函数会根据分配内存的大小,将内存释放回相应的内存池或页缓存中。
需要注意的是,代码中使用了一些其他头文件("Common.h"、"ThreadCache.h"、"PageCache.h"、"ObjectPool.h"),以及一些全局变量和对象(`pTLSThreadCache`、`PageCache::GetInstance()`)。这些部分的实现并未在你提供的代码中包含,所以我无法对其进行详细解释。但根据代码的上下文,可以推测它们可能是用于内存管理的相关组件和数据结构。
相关问题
我的头文件是这样写的#include <stdio.h> #include <math.h> #include <fstream> #include <iostream> #include <string>//getline #include <sstream> #include "stb_image.h" #pragma comment(lib, "openGL32.lib") #pragma comment(lib, "glu32.lib") #pragma comment(lib, "glaux.lib") #include <gl/glaux.h> #include "glew.h" #include "glut.h" #include <vector>,请问如何避免报错gl.h included before glew.h呢
在你的头文件中,应该将 `glew.h` 的引入放在 `gl.h` 的引入之前。因此,你应该将 `glew.h` 的引入语句移到 `gl.h` 的引入语句之前,就像这样:
```
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <string>//getline
#include <sstream>
#include "stb_image.h"
#include <gl/glaux.h>
#include <vector>
#include "glew.h"
#include <gl/glut.h>
#pragma comment(lib, "openGL32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "glaux.lib")
```
这样就能够避免 `gl.h included before glew.h` 的错误了。
阅读全文
相关推荐














