2023-02-13 15:07:58 -05:00
|
|
|
// Copyright (c) 2022-2023 MinIO, Inc.
|
2022-08-25 16:07:15 -04:00
|
|
|
//
|
|
|
|
// This file is part of MinIO Object Storage stack
|
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
|
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2023-02-13 15:07:58 -05:00
|
|
|
package workers
|
2022-08-25 16:07:15 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2023-02-13 15:07:58 -05:00
|
|
|
// Workers provides a bounded semaphore with the ability to wait until all
|
2022-08-25 16:07:15 -04:00
|
|
|
// concurrent jobs finish.
|
2023-02-13 15:07:58 -05:00
|
|
|
type Workers struct {
|
|
|
|
wg sync.WaitGroup
|
|
|
|
queue chan struct{}
|
2022-08-25 16:07:15 -04:00
|
|
|
}
|
|
|
|
|
2023-02-13 15:07:58 -05:00
|
|
|
// New creates a Workers object which allows up to n jobs to proceed
|
2022-08-25 16:07:15 -04:00
|
|
|
// concurrently. n must be > 0.
|
2023-02-13 15:07:58 -05:00
|
|
|
func New(n int) (*Workers, error) {
|
2022-08-25 16:07:15 -04:00
|
|
|
if n <= 0 {
|
|
|
|
return nil, errors.New("n must be > 0")
|
|
|
|
}
|
|
|
|
|
2023-02-13 15:07:58 -05:00
|
|
|
queue := make(chan struct{}, n)
|
2022-08-25 16:07:15 -04:00
|
|
|
for i := 0; i < n; i++ {
|
2023-02-13 15:07:58 -05:00
|
|
|
queue <- struct{}{}
|
2022-08-25 16:07:15 -04:00
|
|
|
}
|
2023-02-13 15:07:58 -05:00
|
|
|
return &Workers{
|
|
|
|
queue: queue,
|
2022-08-25 16:07:15 -04:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Take is how a job (goroutine) can Take its turn.
|
2023-02-13 15:07:58 -05:00
|
|
|
func (jt *Workers) Take() {
|
2022-08-25 16:07:15 -04:00
|
|
|
jt.wg.Add(1)
|
2023-02-13 15:07:58 -05:00
|
|
|
<-jt.queue
|
2022-08-25 16:07:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Give is how a job (goroutine) can give back its turn once done.
|
2023-02-13 15:07:58 -05:00
|
|
|
func (jt *Workers) Give() {
|
|
|
|
jt.queue <- struct{}{}
|
2022-08-25 16:07:15 -04:00
|
|
|
jt.wg.Done()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait waits for all ongoing concurrent jobs to complete
|
2023-02-13 15:07:58 -05:00
|
|
|
func (jt *Workers) Wait() {
|
2022-08-25 16:07:15 -04:00
|
|
|
jt.wg.Wait()
|
|
|
|
}
|