1 /**
2 * Copyright 2019 Huawei Technologies Co., Ltd
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 #include "minddata/dataset/util/cond_var.h"
17
18 #include "minddata/dataset/util/services.h"
19 #include "minddata/dataset/util/task_manager.h"
20
21 namespace mindspore {
22 namespace dataset {
CondVar()23 CondVar::CondVar() : svc_(nullptr), my_name_(Services::GetUniqueID()) {}
24
Wait(std::unique_lock<std::mutex> * lck,const std::function<bool ()> & pred)25 Status CondVar::Wait(std::unique_lock<std::mutex> *lck, const std::function<bool()> &pred) {
26 try {
27 if (svc_ != nullptr) {
28 // If this cv registers with a global resource tracking, then wait unconditionally.
29 auto f = [this, &pred]() -> bool { return (pred() || this->Interrupted()); };
30 cv_.wait(*lck, f);
31 // If we are interrupted, override the return value if this is the master thread.
32 // Master thread is being interrupted mostly because of some thread is reporting error.
33 RETURN_IF_NOT_OK(Task::OverrideInterruptRc(this->GetInterruptStatus()));
34 } else {
35 // Otherwise we wake up once a while to check for interrupt (for this thread).
36 auto f = [&pred]() -> bool { return (pred() || this_thread::is_interrupted()); };
37 while (!f()) {
38 (void)cv_.wait_for(*lck, std::chrono::milliseconds(1));
39 }
40 RETURN_IF_INTERRUPTED();
41 }
42 } catch (const std::exception &e) {
43 RETURN_STATUS_UNEXPECTED(e.what());
44 }
45 return Status::OK();
46 }
47
~CondVar()48 CondVar::~CondVar() noexcept {
49 if (svc_ != nullptr) {
50 (void)svc_->Deregister(my_name_);
51 svc_ = nullptr;
52 }
53 }
54
NotifyOne()55 void CondVar::NotifyOne() noexcept { cv_.notify_one(); }
56
NotifyAll()57 void CondVar::NotifyAll() noexcept { cv_.notify_all(); }
58
Register(std::shared_ptr<IntrpService> svc)59 Status CondVar::Register(std::shared_ptr<IntrpService> svc) {
60 Status rc = svc->Register(my_name_, this);
61 if (rc.IsOk()) {
62 svc_ = svc;
63 }
64 return rc;
65 }
66
Interrupt()67 void CondVar::Interrupt() {
68 IntrpResource::Interrupt();
69 cv_.notify_all();
70 }
71
my_name() const72 std::string CondVar::my_name() const { return my_name_; }
73
Deregister()74 Status CondVar::Deregister() {
75 if (svc_) {
76 Status rc = svc_->Deregister(my_name_);
77 svc_ = nullptr;
78 return rc;
79 }
80 return Status::OK();
81 }
82 } // namespace dataset
83 } // namespace mindspore
84