ref_count.h (1258B)
1 /* Copyright (C) 2013-2023, 2025 Vincent Forest (vaplv@free.fr) 2 * 3 * The RSys library is free software: you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published 5 * by the Free Software Foundation, either version 3 of the License, or 6 * (at your option) any later version. 7 * 8 * The RSys library is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with the RSys library. If not, see <http://www.gnu.org/licenses/>. */ 15 16 #ifndef REF_COUNT_H 17 #define REF_COUNT_H 18 19 #include "rsys.h" 20 21 typedef ATOMIC ref_T; 22 23 static FINLINE void 24 ref_init(ref_T* ref) 25 { 26 ASSERT(NULL != ref); 27 *ref = 1; 28 } 29 30 static FINLINE void 31 ref_get(ref_T* ref) 32 { 33 ASSERT(NULL != ref); 34 ATOMIC_INCR(ref); 35 } 36 37 static FINLINE int 38 ref_put(ref_T* ref, void (*release)(ref_T*)) 39 { 40 ATOMIC curr = 0; 41 ASSERT(NULL != ref); 42 ASSERT(NULL != release); 43 44 curr = ATOMIC_DECR(ref); 45 ASSERT(curr >= 0); 46 47 if(0 == curr) { 48 release(ref); 49 return 1; 50 } 51 return 0; 52 } 53 54 #endif /* REF_COUNT_H */