1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 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 #ifndef TOKEN_H 16 #define TOKEN_H 17 #include <atomic> 18 #include <cstdio> 19 #include <stdlib.h> 20 #include <new> 21 22 namespace ffrt { 23 24 class Token { 25 public: 26 using token_value_t = std::atomic<unsigned int>; 27 28 Token() = delete; Token(unsigned int init)29 Token(unsigned int init) 30 { 31 count.store(init); 32 } 33 try_acquire()34 inline bool try_acquire() 35 { 36 bool ret = true; 37 for (; ;) { 38 unsigned int v = count.load(std::memory_order_relaxed); 39 if (v == 0) { 40 ret = false; 41 break; 42 } 43 if (count.compare_exchange_strong(v, v - 1, std::memory_order_acquire, std::memory_order_relaxed)) { 44 break; 45 } 46 } 47 return ret; 48 } 49 release()50 inline void release() 51 { 52 count.fetch_add(1); 53 } 54 load()55 unsigned int load() 56 { 57 return count.load(); 58 } 59 private: 60 token_value_t count; 61 }; 62 } 63 #endif