github.com/lnzx/goofys@v0.24.0/internal/ticket.go (about) 1 // Copyright 2016 Ka-Hing Cheung 2 // 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 package internal 16 17 import ( 18 "sync" 19 ) 20 21 type Ticket struct { 22 Total uint32 23 24 total uint32 25 outstanding uint32 26 27 mu sync.Mutex 28 cond *sync.Cond 29 } 30 31 func (ticket Ticket) Init() *Ticket { 32 ticket.cond = sync.NewCond(&ticket.mu) 33 ticket.total = ticket.Total 34 return &ticket 35 } 36 37 func (ticket *Ticket) Take(howmany uint32, block bool) (took bool) { 38 ticket.mu.Lock() 39 defer ticket.mu.Unlock() 40 41 for ticket.outstanding+howmany > ticket.total { 42 if block { 43 ticket.cond.Wait() 44 } else { 45 return 46 } 47 } 48 49 ticket.outstanding += howmany 50 took = true 51 return 52 } 53 54 func (ticket *Ticket) Return(howmany uint32) { 55 ticket.mu.Lock() 56 defer ticket.mu.Unlock() 57 58 ticket.outstanding -= howmany 59 ticket.cond.Signal() 60 }