summaryrefslogtreecommitdiffstats
path: root/util/thread/factory.cpp
diff options
context:
space:
mode:
authorDevtools Arcadia <[email protected]>2022-02-07 18:08:42 +0300
committerDevtools Arcadia <[email protected]>2022-02-07 18:08:42 +0300
commit1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch)
treee26c9fed0de5d9873cce7e00bc214573dc2195b7 /util/thread/factory.cpp
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'util/thread/factory.cpp')
-rw-r--r--util/thread/factory.cpp93
1 files changed, 93 insertions, 0 deletions
diff --git a/util/thread/factory.cpp b/util/thread/factory.cpp
new file mode 100644
index 00000000000..48e898f32dc
--- /dev/null
+++ b/util/thread/factory.cpp
@@ -0,0 +1,93 @@
+#include "factory.h"
+
+#include <util/system/thread.h>
+#include <util/generic/singleton.h>
+
+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<TThread> Thr_;
+ };
+
+ inline TSystemThreadFactory() noexcept {
+ }
+
+ IThread* DoCreate() override {
+ return new TPoolThread;
+ }
+ };
+
+ class TThreadFactoryFuncObj: public IThreadFactory::IThreadAble {
+ public:
+ TThreadFactoryFuncObj(const std::function<void()>& func)
+ : Func(func)
+ {
+ }
+ void DoExecute() override {
+ THolder<TThreadFactoryFuncObj> self(this);
+ Func();
+ }
+
+ private:
+ std::function<void()> Func;
+ };
+}
+
+THolder<IThread> IThreadFactory::Run(std::function<void()> func) {
+ THolder<IThread> ret(DoCreate());
+
+ ret->Run(new ::TThreadFactoryFuncObj(func));
+
+ return ret;
+}
+
+static IThreadFactory* SystemThreadPoolImpl() {
+ return Singleton<TSystemThreadFactory>();
+}
+
+static IThreadFactory* systemPool = nullptr;
+
+IThreadFactory* SystemThreadFactory() {
+ if (systemPool) {
+ return systemPool;
+ }
+
+ return SystemThreadPoolImpl();
+}
+
+void SetSystemThreadFactory(IThreadFactory* pool) {
+ systemPool = pool;
+}