aboutsummaryrefslogtreecommitdiff
path: root/weed/util/limiter.go
blob: 2e5168d3d7b1364ec4044d3c1b5bd9d9b0321ce0 (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package util

import (
	"math/rand"
	"reflect"
	"sync"
	"sync/atomic"
)

type OperationRequest func()

type LimitedOutOfOrderProcessor struct {
	processorSlots     uint32
	processors         []chan OperationRequest
	processorLimit     int32
	processorLimitCond *sync.Cond
	currentProcessor   int32
}

func NewLimitedOutOfOrderProcessor(limit int32) (c *LimitedOutOfOrderProcessor) {

	processorSlots := uint32(32)
	c = &LimitedOutOfOrderProcessor{
		processorSlots:     processorSlots,
		processors:         make([]chan OperationRequest, processorSlots),
		processorLimit:     limit,
		processorLimitCond: sync.NewCond(new(sync.Mutex)),
	}

	for i := 0; i < int(processorSlots); i++ {
		c.processors[i] = make(chan OperationRequest)
	}

	cases := make([]reflect.SelectCase, processorSlots)
	for i, ch := range c.processors {
		cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}
	}

	go func() {
		for {
			_, value, ok := reflect.Select(cases)
			if !ok {
				continue
			}

			request := value.Interface().(OperationRequest)

			c.processorLimitCond.L.Lock()
			for atomic.LoadInt32(&c.currentProcessor) > c.processorLimit {
				c.processorLimitCond.Wait()
			}
			atomic.AddInt32(&c.currentProcessor, 1)
			c.processorLimitCond.L.Unlock()

			go func() {
				defer atomic.AddInt32(&c.currentProcessor, -1)
				defer c.processorLimitCond.Signal()
				request()
			}()

		}
	}()

	return c
}

func (c *LimitedOutOfOrderProcessor) Execute(request OperationRequest) {
	index := rand.Uint32() % c.processorSlots
	c.processors[index] <- request
}