-
Notifications
You must be signed in to change notification settings - Fork 0
/
methodUnion.go
53 lines (48 loc) · 892 Bytes
/
methodUnion.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 stringset
import "sync"
// Union returns a new set which contains all elements of the previous ones.
func (s *StringSet) Union(other *StringSet) *StringSet {
var slen, otherlen int
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
s.lock.Lock()
slen = len(s.m)
s.lock.Unlock()
}()
go func() {
defer wg.Done()
other.lock.Lock()
otherlen = len(other.m)
other.lock.Unlock()
}()
wg.Wait()
l := slen + otherlen
ret := &StringSet{
m: make(map[string]struct{}, l),
}
wg.Add(2)
go func() {
defer wg.Done()
s.lock.Lock()
for str := range s.m {
ret.lock.Lock()
ret.m[str] = struct{}{}
ret.lock.Unlock()
}
s.lock.Unlock()
}()
go func() {
defer wg.Done()
other.lock.Lock()
for str := range other.m {
ret.lock.Lock()
ret.m[str] = struct{}{}
ret.lock.Unlock()
}
other.lock.Unlock()
}()
wg.Wait()
return ret
}