InitThreadFactory.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright 2018-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <memory>
  18. #include <thread>
  19. #include <folly/ScopeGuard.h>
  20. #include <folly/executors/thread_factory/ThreadFactory.h>
  21. namespace folly {
  22. class InitThreadFactory : public ThreadFactory {
  23. public:
  24. explicit InitThreadFactory(
  25. std::shared_ptr<ThreadFactory> threadFactory,
  26. Func&& threadInitializer,
  27. Func&& threadFinializer = [] {})
  28. : threadFactory_(std::move(threadFactory)),
  29. threadInitFini_(std::make_shared<ThreadInitFini>(
  30. std::move(threadInitializer),
  31. std::move(threadFinializer))) {}
  32. std::thread newThread(Func&& func) override {
  33. return threadFactory_->newThread(
  34. [func = std::move(func), threadInitFini = threadInitFini_]() mutable {
  35. threadInitFini->initializer();
  36. SCOPE_EXIT {
  37. threadInitFini->finalizer();
  38. };
  39. func();
  40. });
  41. }
  42. private:
  43. std::shared_ptr<ThreadFactory> threadFactory_;
  44. struct ThreadInitFini {
  45. ThreadInitFini(Func&& init, Func&& fini)
  46. : initializer(std::move(init)), finalizer(std::move(fini)) {}
  47. Func initializer;
  48. Func finalizer;
  49. };
  50. std::shared_ptr<ThreadInitFini> threadInitFini_;
  51. };
  52. } // namespace folly