使用c++11的智慧型指標實現乙個簡約版的記憶體池
.**件
//
// created by 李文龍 on 2019/12/1.
//#ifndef thread_tool_test_memory_pool_h
#define thread_tool_test_memory_pool_h
#include
"common.h"
#include
#include
#include
#include
#include
ns_ilong_begin
template
<
class
t>
class
memorypool
;ns_ilong_end
#endif
//thread_tool_test_memory_pool_h
.cpp檔案//
// created by 李文龍 on 2019/12/1.
//#include
"memory_pool.h"
ns_ilong_begin
template
<
class
t>
memorypool
::memorypool
(int maxcount,
const std::string &tag)
:max_buffer_count_
,tag_
template
<
class
t>
memorypool::~
memorypool()
template
<
class
t>
std::shared_ptr memorypool
::getobject()
for(
const std::shared_ptr
&buffer : buffers_)
} std::shared_ptr data = std::make_shared()
; buffers_.
push_back
(data)
;return data;
}template
<
class
t>
void memorypool
::clearallobjects()
template
<
class
t>
int memorypool
::getfreecount()
}return freecount;
}template
<
class
t>
int memorypool
::getusedcount()
}return usedcount;
}ns_ilong_end
測試程式#include
"memory_pool.cpp"
class
databuffer};
intmain()
int count = memorypool.
getfreecount()
;elog_debug
("memory pool count: %d"
, count)
;auto data = memorypool.
getobject()
; count = memorypool.
getfreecount()
;elog_debug
("memory pool count: %d"
, count)
; memory_pool_.
clearallobjects()
; count = memorypool.
getfreecount()
;elog_debug
("memory pool count: %d"
, count)
;}
注意由於模版類是寫在.h和.cpp檔案中,所以使用是要 #include 「memory_pool.cpp」,否則編譯會報錯
原始碼位址
C 11 執行緒池實現
c 11中已經新增了跨平台的thread相關工具,在一些輕量級使用場景中,使用std thread無疑會給我們帶來很多方便。這裡使用它實現了乙個簡單的執行緒池 easythreadpool.h ifndef easy thread pool h define easy thread pool h i...
C 11執行緒池的實現
執行緒池是指定執行緒建立的個數,每個執行緒只是建立銷毀一次。比起毫無限制的建立執行緒銷毀執行緒效率更高。畢竟頻繁的建立銷毀執行緒會消耗系統資源,而且系統建立執行緒也是有上限的。class thread pool thread pool thread pool int n done false els...
C 11 執行緒池簡單實現
話不多說,先上 pragma once include include include include include include include include const int max threads 1000 typedef std function void void task int...