-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsync.go
45 lines (35 loc) · 919 Bytes
/
sync.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
// Copyright (c) 2020 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package longroutine
import "sync"
// SingleStarter should start no more than one (potentially long-running) concurrent go routine for a given key
type SingleStarter interface {
// StartSingle instance of (potentially long-running) routine `f` gets started for the given `key`
StartSingle(key string, f func())
}
// NewSingleStarter creates a SingleStarter
func NewSingleStarter() SingleStarter {
return &syncStarter{
m: map[string]struct{}{},
}
}
type syncStarter struct {
sync.Mutex
m map[string]struct{}
}
func (s *syncStarter) StartSingle(key string, f func()) {
s.Lock()
defer s.Unlock()
if _, exists := s.m[key]; !exists {
go s.run(key, f)
s.m[key] = struct{}{}
}
}
func (s *syncStarter) run(key string, f func()) {
defer func() {
s.Lock()
defer s.Unlock()
delete(s.m, key)
}()
f()
}