1
0

objectpool_test.cpp 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <stdio.h>
  2. #include <thread>
  3. #include "hobjectpool.h"
  4. #ifdef _WIN32
  5. #include <windows.h>
  6. #else
  7. #include <unistd.h>
  8. #endif
  9. void msleep(unsigned int ms) {
  10. #ifdef _WIN32
  11. Sleep(ms);
  12. #else
  13. usleep(ms*1000);
  14. #endif
  15. }
  16. class Task {
  17. public:
  18. Task() {printf("Task()\n");}
  19. ~Task() {printf("~Task()\n");}
  20. void Do() {
  21. printf("%p start do...\n", this);
  22. msleep(4000);
  23. printf("%p end do\n", this);
  24. }
  25. };
  26. HObjectPool<Task> tasks;
  27. void task_thread(int id) {
  28. printf("thread %d run...\n", id);
  29. auto pObj = tasks.Get();
  30. if (pObj) {
  31. pObj->Do();
  32. tasks.Release(pObj);
  33. }
  34. else {
  35. printf("objects too little\n");
  36. }
  37. printf("thread %d exit\n", id);
  38. }
  39. int main(int argc, char** argv) {
  40. tasks.pool_size = 5;
  41. tasks.timeout = 3000;
  42. for (int i = 0; i < 10; ++i) {
  43. new std::thread(task_thread, i);
  44. }
  45. msleep(5000);
  46. for (int i = 10; i < 20; ++i) {
  47. new std::thread(task_thread, i);
  48. }
  49. msleep(10000);
  50. return 0;
  51. }