You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.8KB

  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <chrono>
  11. #include "Util/logger.h"
  12. #include "Util/onceToken.h"
  13. #include "Util/TimeTicker.h"
  14. #include "Thread/ThreadPool.h"
  15. using namespace std;
  16. using namespace toolkit;
  17. int main() {
  18. //初始化日志系统
  19. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  20. Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
  21. ThreadPool pool(thread::hardware_concurrency(), ThreadPool::PRIORITY_HIGHEST, true);
  22. //每个任务耗时3秒
  23. auto task_second = 3;
  24. //每个线程平均执行4次任务,总耗时应该为12秒
  25. auto task_count = thread::hardware_concurrency() * 4;
  26. semaphore sem;
  27. vector<int> vec;
  28. vec.resize(task_count);
  29. Ticker ticker;
  30. {
  31. //放在作用域中确保token引用次数减1
  32. auto token = std::make_shared<onceToken>(nullptr, [&]() {
  33. sem.post();
  34. });
  35. for (auto i = 0; i < task_count; ++i) {
  36. pool.async([token, i, task_second, &vec]() {
  37. setThreadName(("thread pool " + to_string(i)).data());
  38. std::this_thread::sleep_for(std::chrono::seconds(task_second)); //休眠三秒
  39. InfoL << "task " << i << " done!";
  40. vec[i] = i;
  41. });
  42. }
  43. }
  44. sem.wait();
  45. InfoL << "all task done, used milliseconds:" << ticker.elapsedTime();
  46. //打印执行结果
  47. for (auto i = 0; i < task_count; ++i) {
  48. InfoL << vec[i];
  49. }
  50. return 0;
  51. }