example_tc_mem_chunk.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #include "util/tc_mem_chunk.h"
  17. #include "util/tc_sem_mutex.h"
  18. #include "util/tc_shm.h"
  19. #include "util/tc_mmap.h"
  20. #include "util/tc_file.h"
  21. #include "util/tc_option.h"
  22. #include "util/tc_common.h"
  23. #include <sstream>
  24. #include <iostream>
  25. using namespace tars;
  26. TC_Mmap m;
  27. TC_MemMultiChunkAllocator alloc;
  28. void testAllocate()
  29. {
  30. vector<size_t> b = alloc.getBlockSize();
  31. cout << TC_Common::tostr(b) << endl;
  32. cout << alloc.allBlockChunkCount() << endl;
  33. vector<void*> v;
  34. size_t n = 77;
  35. while(true)
  36. {
  37. size_t iAllocSize;
  38. void *p = alloc.allocate(n, iAllocSize);
  39. cout << p << endl;
  40. if(!p)
  41. {
  42. break;
  43. }
  44. v.push_back(p);
  45. n += 2;
  46. }
  47. cout << v.size() << endl;
  48. for(size_t i = 0; i < v.size(); i++)
  49. {
  50. alloc.deallocate(v[i]);
  51. }
  52. }
  53. int main(int argc, char *argv[])
  54. {
  55. try
  56. {
  57. TC_Option option;
  58. option.decode(argc, argv);
  59. if(TC_File::isFileExist("mc.hmap"))
  60. {
  61. m.mmap("mc.hmap", TC_File::getFileSize("mc.hmap"));
  62. }
  63. else
  64. {
  65. m.mmap("mc.hmap", 1204);
  66. }
  67. if(m.iscreate())
  68. {
  69. alloc.create(m.getPointer(), m.getSize(), 30, 100, 1.2);
  70. }
  71. else
  72. {
  73. alloc.connect(m.getPointer());
  74. }
  75. if(option.hasParam("append"))
  76. {
  77. size_t i = m.getSize() * 3;
  78. m.munmap();
  79. m.mmap("mc.hmap", i);
  80. alloc.append(m.getPointer(), i);
  81. m.munmap();
  82. m.mmap("mc.hmap", i*3);
  83. alloc.append(m.getPointer(), i*3);
  84. m.munmap();
  85. m.mmap("mc.hmap", i*5);
  86. alloc.append(m.getPointer(), i*5);
  87. }
  88. else if(option.hasParam("alloc"))
  89. {
  90. testAllocate();
  91. }
  92. }
  93. catch(exception &ex)
  94. {
  95. cout << ex.what() << endl;
  96. }
  97. return 0;
  98. }