factory.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "factory.h"
  2. #include <util/system/thread.h>
  3. #include <util/generic/singleton.h>
  4. using IThread = IThreadFactory::IThread;
  5. namespace {
  6. class TSystemThreadFactory: public IThreadFactory {
  7. public:
  8. class TPoolThread: public IThread {
  9. public:
  10. ~TPoolThread() override {
  11. if (Thr_) {
  12. Thr_->Detach();
  13. }
  14. }
  15. void DoRun(IThreadAble* func) override {
  16. Thr_.Reset(new TThread(ThreadProc, func));
  17. Thr_->Start();
  18. }
  19. void DoJoin() noexcept override {
  20. if (!Thr_) {
  21. return;
  22. }
  23. Thr_->Join();
  24. Thr_.Destroy();
  25. }
  26. private:
  27. static void* ThreadProc(void* func) {
  28. ((IThreadAble*)(func))->Execute();
  29. return nullptr;
  30. }
  31. private:
  32. THolder<TThread> Thr_;
  33. };
  34. inline TSystemThreadFactory() noexcept {
  35. }
  36. IThread* DoCreate() override {
  37. return new TPoolThread;
  38. }
  39. };
  40. class TThreadFactoryFuncObj: public IThreadFactory::IThreadAble {
  41. public:
  42. TThreadFactoryFuncObj(const std::function<void()>& func)
  43. : Func(func)
  44. {
  45. }
  46. void DoExecute() override {
  47. THolder<TThreadFactoryFuncObj> self(this);
  48. Func();
  49. }
  50. private:
  51. std::function<void()> Func;
  52. };
  53. } // namespace
  54. THolder<IThread> IThreadFactory::Run(const std::function<void()>& func) {
  55. THolder<IThread> ret(DoCreate());
  56. ret->Run(new ::TThreadFactoryFuncObj(func));
  57. return ret;
  58. }
  59. static IThreadFactory* SystemThreadPoolImpl() {
  60. return Singleton<TSystemThreadFactory>();
  61. }
  62. static IThreadFactory* systemPool = nullptr;
  63. IThreadFactory* SystemThreadFactory() {
  64. if (systemPool) {
  65. return systemPool;
  66. }
  67. return SystemThreadPoolImpl();
  68. }
  69. void SetSystemThreadFactory(IThreadFactory* pool) {
  70. systemPool = pool;
  71. }