forked from seiflotfy/cuckoofilter
-
Notifications
You must be signed in to change notification settings - Fork 13
/
example_threadsafe_test.go
63 lines (53 loc) · 1.17 KB
/
example_threadsafe_test.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
package cuckoo_test
import (
"fmt"
"sync"
cuckoo "github.com/panmari/cuckoofilter"
)
// Small wrapper around cuckoo filter making it thread safe.
type threadSafeFilter struct {
cf *cuckoo.Filter
mu sync.RWMutex
}
func (f *threadSafeFilter) insert(item []byte) {
// Concurrent inserts need a Write lock.
f.mu.Lock()
defer f.mu.Unlock()
f.cf.Insert(item)
}
func (f *threadSafeFilter) lookup(item []byte) bool {
// Concurrent lookups need a read lock.
f.mu.RLock()
defer f.mu.RUnlock()
return f.cf.Lookup(item)
}
func Example_threadSafe() {
cf := &threadSafeFilter{
cf: cuckoo.NewFilter(1000),
}
var wg sync.WaitGroup
// Insert items concurrently...
for i := byte(0); i < 50; i++ {
wg.Add(1)
go func(item byte) {
defer wg.Done()
cf.insert([]byte{item})
}(i)
}
// ...while also doing lookups concurrently.
for i := byte(0); i < 100; i++ {
wg.Add(1)
go func(item byte) {
defer wg.Done()
// State is not well-defined here, so we can't define expectations.
cf.lookup([]byte{item})
}(i)
}
wg.Wait()
// Simple lookups to verify initialization.
fmt.Println(cf.lookup([]byte{1}))
fmt.Println(cf.lookup([]byte{99}))
// Output:
// true
// false
}