executor_ut.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include "gtest/gtest.h"
  4. #include "alibabacloud/core/Runnable.h"
  5. #include "../src/Executor.h"
  6. using namespace std;
  7. using namespace AlibabaCloud;
  8. namespace {
  9. static unsigned int nbr = 0;
  10. static void f0() {
  11. usleep(3000);
  12. nbr |= 0x01;
  13. }
  14. static void f1() {
  15. usleep(3000);
  16. nbr |= 0x02;
  17. }
  18. static void f2() {
  19. usleep(3000);
  20. nbr |= 0x04;
  21. }
  22. // there should be no exception
  23. TEST(Executor, basic) {
  24. std::function<void()> func0(f0);
  25. std::function<void()> func1(f1);
  26. std::function<void()> func2(f2);
  27. Runnable* rf0 = new Runnable(func0);
  28. Runnable* rf1 = new Runnable(func1);
  29. Runnable* rf2 = new Runnable(func2);
  30. Executor* e = new Executor;
  31. EXPECT_TRUE(e->isShutdown() == true);
  32. // thread created to execute tasks
  33. e->start();
  34. // before
  35. EXPECT_TRUE(nbr == 0);
  36. // push tasks to queue
  37. e->instance()->execute(rf0);
  38. e->instance()->execute(rf1);
  39. e->instance()->execute(rf2);
  40. // shutdown removes tasks in queue
  41. e->shutdown();
  42. // there is no time for task executing
  43. // maybe some tasks executed as the async reason
  44. // EXPECT_EQ(nbr, 0x07);
  45. rf0 = new Runnable(func0);
  46. rf1 = new Runnable(func1);
  47. rf2 = new Runnable(func2);
  48. nbr = 0;
  49. e->execute(rf0);
  50. usleep(5000);
  51. // executor not started, nbr no changed
  52. EXPECT_TRUE(nbr == 0);
  53. e->start();
  54. // there should be no more thread created
  55. e->start();
  56. e->instance()->execute(rf0);
  57. e->execute(rf1);
  58. e->execute(rf2);
  59. usleep(20000);
  60. // EXPECT_EQ(nbr, 0x07);
  61. e->shutdown();
  62. }
  63. }