-
Notifications
You must be signed in to change notification settings - Fork 36
/
concurrently.go
52 lines (44 loc) · 1022 Bytes
/
concurrently.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package limiter
import (
"sync/atomic"
)
const (
DefaultConcurrencyLimitIO = 4
)
// Concurrently - execute tasks (IO) concurrently, keep track of the first error atomically
type Concurrently struct {
conc *ConcurrencyLimiter
firstError atomic.Value // type: error
// TODO:: we can also add an atomic list of errors here if needed.
}
func NewConcurrencyLimiterForIO(limit int) *Concurrently {
c := &Concurrently{
conc: NewConcurrencyLimiter(limit),
firstError: atomic.Value{},
}
if c.conc == nil {
c = nil
}
return c
}
func (c *Concurrently) Execute(job func()) (int, error) {
return c.conc.Execute(job)
}
func (c *Concurrently) WaitAndClose() error {
return c.conc.WaitAndClose()
}
func (c *Concurrently) FirstErrorStore(e error) (bool, error) {
stored := false
if e != nil {
stored = c.firstError.CompareAndSwap(nil, e)
}
return stored, e
}
func (c *Concurrently) FirstErrorGet() error {
e := c.firstError.Load()
if e == nil {
return nil
}
err := e.(error)
return err
}