1
0

objectpool_test.cpp 987 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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> task_pool(1, 5);
  27. void task_thread(int id) {
  28. printf("thread %d run...\n", id);
  29. HPoolObject<Task> pTask(task_pool);
  30. if (pTask) {
  31. pTask->Do();
  32. }
  33. else {
  34. printf("No available task in pool\n");
  35. }
  36. printf("thread %d exit\n", id);
  37. }
  38. int main(int argc, char** argv) {
  39. for (int i = 0; i < 10; ++i) {
  40. new std::thread(task_thread, i);
  41. }
  42. msleep(5000);
  43. for (int i = 10; i < 20; ++i) {
  44. new std::thread(task_thread, i);
  45. }
  46. msleep(10000);
  47. return 0;
  48. }