TaskQueue.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/xia-chu/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. #ifndef TASKQUEUE_H_
  11. #define TASKQUEUE_H_
  12. #include <list>
  13. #include <deque>
  14. #include <atomic>
  15. #include <mutex>
  16. #include <functional>
  17. #include "Util/List.h"
  18. #include "semaphore.h"
  19. using namespace std;
  20. namespace toolkit {
  21. //实现了一个基于函数对象的任务列队,该列队是线程安全的,任务列队任务数由信号量控制
  22. template<typename T>
  23. class TaskQueue {
  24. public:
  25. //打入任务至列队
  26. template<typename C>
  27. void push_task(C &&task_func) {
  28. {
  29. lock_guard<decltype(_mutex)> lock(_mutex);
  30. _queue.emplace_back(std::forward<C>(task_func));
  31. }
  32. _sem.post();
  33. }
  34. template<typename C>
  35. void push_task_first(C &&task_func) {
  36. {
  37. lock_guard<decltype(_mutex)> lock(_mutex);
  38. _queue.emplace_front(std::forward<C>(task_func));
  39. }
  40. _sem.post();
  41. }
  42. //清空任务列队
  43. void push_exit(size_t n) {
  44. _sem.post(n);
  45. }
  46. //从列队获取一个任务,由执行线程执行
  47. bool get_task(T &tsk) {
  48. _sem.wait();
  49. lock_guard<decltype(_mutex)> lock(_mutex);
  50. if (_queue.size() == 0) {
  51. return false;
  52. }
  53. //改成右值引用后性能提升了1倍多!
  54. tsk = std::move(_queue.front());
  55. _queue.pop_front();
  56. return true;
  57. }
  58. size_t size() const{
  59. lock_guard<decltype(_mutex)> lock(_mutex);
  60. return _queue.size();
  61. }
  62. private:
  63. //经过对比List,std::list,std::deque三种容器发现,
  64. //在i5-6200U单线程环境下,执行1000万个任务时,分别耗时1.3,2.4,1.8秒左右
  65. //所以此处我们替换成性能最好的List模板
  66. List<T> _queue;
  67. mutable mutex _mutex;
  68. semaphore _sem;
  69. };
  70. } /* namespace toolkit */
  71. #endif /* TASKQUEUE_H_ */