example_tc_autoptr.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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_autoptr.h"
  17. #include "util/tc_thread_pool.h"
  18. #include <vector>
  19. #include <cassert>
  20. #include <iostream>
  21. using namespace std;
  22. using namespace tars;
  23. void func(int &i)
  24. {
  25. }
  26. class TestPointer : public TC_HandleBase
  27. {
  28. public:
  29. void func(int &i)
  30. {
  31. int n = 10000;
  32. while(n)
  33. {
  34. i++;
  35. n--;
  36. }
  37. }
  38. };
  39. void test()
  40. {
  41. int i = 0;
  42. typedef TC_AutoPtr<TestPointer> TestPointerPtr;
  43. vector<TestPointerPtr> vtp;
  44. for(size_t j = 0; j < 10; j++)
  45. {
  46. vtp.push_back(new TestPointer());
  47. }
  48. cout << i << endl;
  49. for(size_t j = 0; j < 10; j++)
  50. {
  51. vtp[j]->func(i);
  52. }
  53. cout << i << endl;
  54. vector<TestPointerPtr> vtp1 = vtp;
  55. for(size_t j = 0; j < 10; j++)
  56. {
  57. vtp[j]->func(i);
  58. }
  59. cout << i << endl;
  60. }
  61. TC_Atomic a;
  62. void testAdd()
  63. {
  64. int i = 10000000;
  65. while(i--)
  66. {
  67. a.inc();
  68. }
  69. }
  70. void testDel()
  71. {
  72. int i = 10000000;
  73. while(i--)
  74. {
  75. a.dec();
  76. }
  77. }
  78. int main(int argc, char *argv[])
  79. {
  80. try
  81. {
  82. cout << a.get() << endl;
  83. TC_ThreadPool tpoolA;
  84. tpoolA.init(10);
  85. tpoolA.start();
  86. TC_ThreadPool tpoolB;
  87. tpoolB.init(10);
  88. tpoolB.start();
  89. {
  90. for(size_t i = 0; i < tpoolA.getThreadNum(); i++)
  91. {
  92. tpoolA.exec(testAdd);
  93. }
  94. }
  95. {
  96. for(size_t i = 0; i < tpoolB.getThreadNum(); i++)
  97. {
  98. tpoolB.exec(testDel);
  99. }
  100. }
  101. tpoolA.waitForAllDone();
  102. tpoolB.waitForAllDone();
  103. cout << a.get() << endl;
  104. }
  105. catch(exception &ex)
  106. {
  107. cout << ex.what() << endl;
  108. }
  109. return 0;
  110. }