github.com/minio/minio@v0.0.0-20240328213742-3f72439b8a27/internal/config/lambda/target/lazyinit.go (about) 1 // Copyright (c) 2015-2023 MinIO, Inc. 2 // 3 // This file is part of MinIO Object Storage stack 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package target 19 20 import ( 21 "sync" 22 "sync/atomic" 23 ) 24 25 // Inspired from Golang sync.Once but it is only marked 26 // initialized when the provided function returns nil. 27 28 type lazyInit struct { 29 done uint32 30 m sync.Mutex 31 } 32 33 func (l *lazyInit) Do(f func() error) error { 34 if atomic.LoadUint32(&l.done) == 0 { 35 return l.doSlow(f) 36 } 37 return nil 38 } 39 40 func (l *lazyInit) doSlow(f func() error) error { 41 l.m.Lock() 42 defer l.m.Unlock() 43 if atomic.LoadUint32(&l.done) == 0 { 44 if err := f(); err != nil { 45 return err 46 } 47 // Mark as done only when f() is successful 48 atomic.StoreUint32(&l.done, 1) 49 } 50 return nil 51 }