threadgroup.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. #ifndef THREADGROUP_H_
  11. #define THREADGROUP_H_
  12. #include <stdexcept>
  13. #include <thread>
  14. #include <unordered_map>
  15. namespace toolkit {
  16. class thread_group {
  17. private:
  18. thread_group(thread_group const &);
  19. thread_group &operator=(thread_group const &);
  20. public:
  21. thread_group() {}
  22. ~thread_group() {
  23. _threads.clear();
  24. }
  25. bool is_this_thread_in() {
  26. auto thread_id = std::this_thread::get_id();
  27. if (_thread_id == thread_id) {
  28. return true;
  29. }
  30. return _threads.find(thread_id) != _threads.end();
  31. }
  32. bool is_thread_in(std::thread *thrd) {
  33. if (!thrd) {
  34. return false;
  35. }
  36. auto it = _threads.find(thrd->get_id());
  37. return it != _threads.end();
  38. }
  39. template<typename F>
  40. std::thread *create_thread(F &&threadfunc) {
  41. auto thread_new = std::make_shared<std::thread>(threadfunc);
  42. _thread_id = thread_new->get_id();
  43. _threads[_thread_id] = thread_new;
  44. return thread_new.get();
  45. }
  46. void remove_thread(std::thread *thrd) {
  47. auto it = _threads.find(thrd->get_id());
  48. if (it != _threads.end()) {
  49. _threads.erase(it);
  50. }
  51. }
  52. void join_all() {
  53. if (is_this_thread_in()) {
  54. throw std::runtime_error("Trying joining itself in thread_group");
  55. }
  56. for (auto &it : _threads) {
  57. if (it.second->joinable()) {
  58. it.second->join(); //等待线程主动退出
  59. }
  60. }
  61. _threads.clear();
  62. }
  63. size_t size() {
  64. return _threads.size();
  65. }
  66. private:
  67. std::thread::id _thread_id;
  68. std::unordered_map<std::thread::id, std::shared_ptr<std::thread>> _threads;
  69. };
  70. } /* namespace toolkit */
  71. #endif /* THREADGROUP_H_ */