GO·NOTE

一份 Go 开发工程师的学习笔记

0%

自制并发安全的set

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 main

import (
"fmt"
"sync"
"time"
)

type threadSafeSet struct {
sync.RWMutex
data map[interface{}]interface{}
}

func (set *threadSafeSet)Add(item interface{}) {
// map is not safe in concurrency
set.Lock()
set.data[item] = true
set.Unlock()
}

func (set *threadSafeSet)Remove(item interface{}) {
set.Lock()
delete(set.data,item)
set.Unlock()
}

func (set *threadSafeSet) Iter() <-chan interface{} {
ch := make(chan interface{})
go func() {
set.RLock()
for item,_ := range set.data {
ch <- item
}
close(ch)
set.RUnlock()

}()
return ch
}

func main() {
set := new(threadSafeSet)
set.data = make(map[interface{}]interface{})
for i:=0;i<100 ;i++ {
set.Add(i)
}

for item := range set.Iter(){
fmt.Printf("get value from set,value is %v\n",item)
}

time.Sleep(5 * time.Second)
}