-
Notifications
You must be signed in to change notification settings - Fork 0
/
coordinate_supplier_rwmutex.go
53 lines (46 loc) · 1.31 KB
/
coordinate_supplier_rwmutex.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
53
package coordinate_supplier
import (
"fmt"
"sync"
)
type coordinateSupplierRWMutex struct {
coordinates []Coordinate
at int
repeat bool
order Order
rw sync.RWMutex
}
// NewCoordinateSupplierRWMutex returns a CoordinateSupplier synchronized with sync.RWMutex.
// It blocks more and is slower than NewCoordinateSupplierAtomic, but the coordinates are guaranteed to be handed out strictly in-order when used concurrently.
func NewCoordinateSupplierRWMutex(opts CoordinateSupplierOptions) (CoordinateSupplier, error) {
if opts.Width < 1 {
return nil, fmt.Errorf("minimum width is 1")
}
if opts.Height < 1 {
return nil, fmt.Errorf("minimum height is 1")
}
coords, err := MakeCoordinateList(opts.Width, opts.Height, opts.Order)
if err != nil {
return nil, fmt.Errorf("failed make coordinate list: %w", err)
}
cs := &coordinateSupplierRWMutex{
repeat: opts.Repeat,
rw: sync.RWMutex{},
coordinates: coords,
}
return cs, nil
}
// Next returns the next coordinate to be supplied.
func (c *coordinateSupplierRWMutex) Next() (x, y int, done bool) {
c.rw.Lock()
defer c.rw.Unlock()
if c.at >= len(c.coordinates) {
if c.repeat {
c.at = 0
} else {
return 0, 0, true
}
}
defer func() { c.at++ }()
return c.coordinates[c.at].X, c.coordinates[c.at].Y, false
}