1 | /* Copyright 2019 Google LLC. All Rights Reserved. |
2 | |
3 | Licensed under the Apache License, Version 2.0 (the "License"); |
4 | you may not use this file except in compliance with the License. |
5 | You may obtain a copy of the License at |
6 | |
7 | http://www.apache.org/licenses/LICENSE-2.0 |
8 | |
9 | Unless required by applicable law or agreed to in writing, software |
10 | distributed under the License is distributed on an "AS IS" BASIS, |
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | See the License for the specific language governing permissions and |
13 | limitations under the License. |
14 | ==============================================================================*/ |
15 | |
16 | #include "ruy/wait.h" |
17 | |
18 | #include <chrono> // NOLINT(build/c++11) |
19 | |
20 | namespace ruy { |
21 | |
22 | void Wait(const std::function<bool()>& condition, const Duration& spin_duration, |
23 | std::condition_variable* condvar, std::mutex* mutex) { |
24 | // First, trivial case where the `condition` is already true; |
25 | if (condition()) { |
26 | return; |
27 | } |
28 | |
29 | // Then, if spin_duration is nonzero, try busy-waiting. |
30 | if (spin_duration.count() > 0) { |
31 | const TimePoint wait_start = Now(); |
32 | while (Now() - wait_start < spin_duration) { |
33 | if (condition()) { |
34 | return; |
35 | } |
36 | } |
37 | } |
38 | |
39 | // Finally, do real passive waiting. |
40 | std::unique_lock<std::mutex> lock(*mutex); |
41 | condvar->wait(lock, condition); |
42 | } |
43 | |
44 | } // namespace ruy |
45 | |