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 | |
17 | #pragma once |
18 | |
19 | #include <folly/executors/thread_factory/ThreadFactory.h> |
20 | |
21 | #include <folly/String.h> |
22 | #include <folly/portability/SysResource.h> |
23 | #include <folly/portability/SysTime.h> |
24 | |
25 | namespace folly { |
26 | |
27 | /** |
28 | * A ThreadFactory that sets nice values for each thread. The main |
29 | * use case for this class is if there are multiple |
30 | * CPUThreadPoolExecutors in a single process, or between multiple |
31 | * processes, where some should have a higher priority than the others. |
32 | * |
33 | * Note that per-thread nice values are not POSIX standard, but both |
34 | * pthreads and linux support per-thread nice. The default linux |
35 | * scheduler uses these values to do smart thread prioritization. |
36 | * sched_priority function calls only affect real-time schedulers. |
37 | */ |
38 | class PriorityThreadFactory : public ThreadFactory { |
39 | public: |
40 | explicit PriorityThreadFactory( |
41 | std::shared_ptr<ThreadFactory> factory, |
42 | int priority) |
43 | : factory_(std::move(factory)), priority_(priority) {} |
44 | |
45 | std::thread newThread(Func&& func) override { |
46 | int priority = priority_; |
47 | return factory_->newThread([priority, func = std::move(func)]() mutable { |
48 | if (setpriority(PRIO_PROCESS, 0, priority) != 0) { |
49 | LOG(ERROR) << "setpriority failed (are you root?) with error " << errno, |
50 | errnoStr(errno); |
51 | } |
52 | func(); |
53 | }); |
54 | } |
55 | |
56 | private: |
57 | std::shared_ptr<ThreadFactory> factory_; |
58 | int priority_; |
59 | }; |
60 | |
61 | } // namespace folly |
62 | |