-
Notifications
You must be signed in to change notification settings - Fork 90
/
ack.go
64 lines (54 loc) · 1.21 KB
/
ack.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
54
55
56
57
58
59
60
61
62
63
64
package socket
import (
"errors"
"sync"
)
var (
ErrorWaiterNotFound = errors.New("Waiter not found")
)
/**
Processes functions that require answers, also known as acknowledge or ack
*/
type ackProcessor struct {
counter int
counterLock sync.Mutex
resultWaiters map[int](chan string)
resultWaitersLock sync.RWMutex
}
/**
get next id of ack call
*/
func (a *ackProcessor) getNextId() int {
a.counterLock.Lock()
defer a.counterLock.Unlock()
a.counter++
return a.counter
}
/**
Just before the ack function called, the waiter should be added
to wait and receive response to ack call
*/
func (a *ackProcessor) addWaiter(id int, w chan string) {
a.resultWaitersLock.Lock()
a.resultWaiters[id] = w
a.resultWaitersLock.Unlock()
}
/**
removes waiter that is unnecessary anymore
*/
func (a *ackProcessor) removeWaiter(id int) {
a.resultWaitersLock.Lock()
delete(a.resultWaiters, id)
a.resultWaitersLock.Unlock()
}
/**
check if waiter with given ack id is exists, and returns it
*/
func (a *ackProcessor) getWaiter(id int) (chan string, error) {
a.resultWaitersLock.RLock()
defer a.resultWaitersLock.RUnlock()
if waiter, ok := a.resultWaiters[id]; ok {
return waiter, nil
}
return nil, ErrorWaiterNotFound
}