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 #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_SEMAPHORE_H_ 17 #define MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_SEMAPHORE_H_ 18 19 #include "minddata/dataset/util/cond_var.h" 20 21 namespace mindspore { 22 namespace dataset { 23 class TaskGroup; 24 25 /// \brief A counting semaphore. There are two external functions P and V. P decrements the internal count and will be 26 /// blocked if the count is 0 (zero). V increments the internal count and wake up one of the waiters. 27 class Semaphore { 28 public: 29 /// \brief Constructor 30 /// \param init Initial value of the internal counter. Semaphore(int init)31 explicit Semaphore(int init) : value_(init) {} 32 ~Semaphore()33 virtual ~Semaphore() {} 34 /// \brief Decrement the internal counter. Will be blocked if the value is 0. 35 /// \return Error code. Can get interrupt. 36 Status P(); 37 /// \brief Increment the internal counter. Wake up on of the waiters if any. 38 void V(); 39 /// \brief Peek the internal value 40 /// \return The internal value 41 int Peek() const; 42 Status Register(TaskGroup *vg); 43 Status Deregister(); 44 void ResetIntrpState(); 45 46 private: 47 int value_; 48 49 std::mutex mutex_; 50 CondVar wait_cond_; 51 }; 52 } // namespace dataset 53 } // namespace mindspore 54 #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_SEMAPHORE_H_ 55