NamedThreadFactory.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright 2017-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 <atomic>
  18. #include <string>
  19. #include <thread>
  20. #include <folly/Conv.h>
  21. #include <folly/Range.h>
  22. #include <folly/executors/thread_factory/ThreadFactory.h>
  23. #include <folly/system/ThreadName.h>
  24. namespace folly {
  25. class NamedThreadFactory : public ThreadFactory {
  26. public:
  27. explicit NamedThreadFactory(folly::StringPiece prefix)
  28. : prefix_(prefix.str()), suffix_(0) {}
  29. std::thread newThread(Func&& func) override {
  30. auto name = folly::to<std::string>(prefix_, suffix_++);
  31. return std::thread(
  32. [func = std::move(func), name = std::move(name)]() mutable {
  33. folly::setThreadName(name);
  34. func();
  35. });
  36. }
  37. void setNamePrefix(folly::StringPiece prefix) {
  38. prefix_ = prefix.str();
  39. }
  40. std::string getNamePrefix() {
  41. return prefix_;
  42. }
  43. private:
  44. std::string prefix_;
  45. std::atomic<uint64_t> suffix_;
  46. };
  47. } // namespace folly