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 | |
17 | #include <folly/executors/TimedDrivableExecutor.h> |
18 | |
19 | #include <cstring> |
20 | #include <ctime> |
21 | #include <string> |
22 | #include <tuple> |
23 | |
24 | namespace folly { |
25 | |
26 | void TimedDrivableExecutor::add(Func callback) { |
27 | queue_.enqueue(std::move(callback)); |
28 | } |
29 | |
30 | void TimedDrivableExecutor::drive() noexcept { |
31 | wait(); |
32 | run(); |
33 | } |
34 | |
35 | size_t TimedDrivableExecutor::run() noexcept { |
36 | size_t count = 0; |
37 | size_t n = queue_.size(); |
38 | |
39 | // If we have waited already, then func_ may have a value |
40 | if (func_) { |
41 | auto f = std::move(func_); |
42 | f(); |
43 | count = 1; |
44 | } |
45 | |
46 | while (count < n && queue_.try_dequeue(func_)) { |
47 | auto f = std::move(func_); |
48 | f(); |
49 | ++count; |
50 | } |
51 | |
52 | return count; |
53 | } |
54 | |
55 | size_t TimedDrivableExecutor::drain() noexcept { |
56 | size_t tasksRun = 0; |
57 | size_t tasksForSingleRun = 0; |
58 | while ((tasksForSingleRun = run()) != 0) { |
59 | tasksRun += tasksForSingleRun; |
60 | } |
61 | return tasksRun; |
62 | } |
63 | |
64 | void TimedDrivableExecutor::wait() noexcept { |
65 | if (!func_) { |
66 | queue_.dequeue(func_); |
67 | } |
68 | } |
69 | |
70 | } // namespace folly |
71 |