threadgroup.h 2.1 KB

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