#include "factory.h" #include #include using IThread = IThreadFactory::IThread; namespace { class TSystemThreadFactory: public IThreadFactory { public: class TPoolThread: public IThread { public: ~TPoolThread() override { if (Thr_) { Thr_->Detach(); } } void DoRun(IThreadAble* func) override { Thr_.Reset(new TThread(ThreadProc, func)); Thr_->Start(); } void DoJoin() noexcept override { if (!Thr_) { return; } Thr_->Join(); Thr_.Destroy(); } private: static void* ThreadProc(void* func) { ((IThreadAble*)(func))->Execute(); return nullptr; } private: THolder Thr_; }; inline TSystemThreadFactory() noexcept { } IThread* DoCreate() override { return new TPoolThread; } }; class TThreadFactoryFuncObj: public IThreadFactory::IThreadAble { public: TThreadFactoryFuncObj(const std::function& func) : Func(func) { } void DoExecute() override { THolder self(this); Func(); } private: std::function Func; }; } // namespace THolder IThreadFactory::Run(const std::function& func) { THolder ret(DoCreate()); ret->Run(new ::TThreadFactoryFuncObj(func)); return ret; } static IThreadFactory* SystemThreadPoolImpl() { return Singleton(); } static IThreadFactory* systemPool = nullptr; IThreadFactory* SystemThreadFactory() { if (systemPool) { return systemPool; } return SystemThreadPoolImpl(); } void SetSystemThreadFactory(IThreadFactory* pool) { systemPool = pool; }