请选择 进入手机版 | 继续访问电脑版
查看: 411|回复: 0

[运维管理] ACE_Cached_Allocator和ACE_Dynamic_Cached_Allocator的使用方式

688

主题

688

帖子

2083

积分

猿er

Rank: 1

积分
2083
发表于 2016-8-14 17:50:13
依赖c++ ACE(ADAPTIVE Communication Environment)库
  1. #include <ace/Malloc_T.h>
  2. #include <list>
  3. #include <string>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdarg.h>
  7. using namespace std;
  8. struct BufferByte64
  9. {
  10. char byte64[64];
  11. };
  12. class Trace
  13. {
  14. public:
  15. Trace(string n):
  16. m_name(n) {
  17. log("in %s\n", m_name.c_str());
  18. ++m_tab_count;
  19. }
  20. ~Trace() {
  21. --m_tab_count;
  22. log("out %s\n", m_name.c_str());
  23. }
  24. static void log(const char *fmt, ...) {
  25. for(size_t var = 0; var < m_tab_count; ++var)
  26. {
  27. printf("\t");
  28. }
  29. va_list ap;
  30. va_start(ap, fmt);
  31. vprintf(fmt, ap);
  32. va_end(ap);
  33. }
  34. private:
  35. string m_name;
  36. static size_t m_tab_count;
  37. };
  38. size_t Trace::m_tab_count = 0;
  39. typedef ACE_Cached_Allocator<BufferByte64, ACE_Thread_Mutex> CachedAllocator;
  40. int test_cached_allocator(int argc, char *argv[])
  41. {
  42. Trace a("CachedAllocator");
  43. CachedAllocator allocator(100);
  44. list<BufferByte64*> cache_list;
  45. for (int var = 0; var < 200; ++var) {
  46. BufferByte64 *buf = (BufferByte64*)allocator.malloc();
  47. if (NULL != buf)
  48. {
  49. cache_list.push_back(buf);
  50. Trace::log("malloc %p, index = %d, depth=%ld\n", buf, var, allocator.pool_depth());
  51. }
  52. else
  53. {
  54. Trace::log("malloc error, index = %d, depth=%ld\n", var, allocator.pool_depth());
  55. }
  56. }
  57. for (list<BufferByte64*>::iterator iter = cache_list.begin(); iter != cache_list.end(); ++iter)
  58. {
  59. allocator.free(*iter);
  60. }
  61. return 0;
  62. }
  63. int test_dynamic_cache_allocator(int argc, char *argv[])
  64. {
  65. Trace a("DynamicCachedAllocator");
  66. typedef ACE_Dynamic_Cached_Allocator<ACE_Thread_Mutex> DynamicCachedAllocator;
  67. list<void *> cache_list;
  68. DynamicCachedAllocator allocator(100, 64);
  69. for (int var = 0; var < 200; ++var) {
  70. void *buf = allocator.malloc();
  71. if (NULL != buf)
  72. {
  73. cache_list.push_back(buf);
  74. Trace::log("malloc %p, index = %d, depth=%ld\n", buf, var, allocator.pool_depth());
  75. }
  76. else
  77. {
  78. Trace::log("malloc error, index = %d, depth=%ld\n", var, allocator.pool_depth());
  79. }
  80. }
  81. for (list<void*>::iterator iter = cache_list.begin(); iter != cache_list.end(); ++iter)
  82. {
  83. allocator.free(*iter);
  84. }
  85. return 0;
  86. }
  87. int main(int argc, char *argv[])
  88. {
  89. Trace a("main");
  90. test_cached_allocator(argc, argv);
  91. test_dynamic_cache_allocator(argc, argv);
  92. return 0;
  93. }
复制代码


回复

使用道具 举报