-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (58 loc) · 1.43 KB
/
main.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
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"math/rand"
"sync"
"github.com/guilhermeCoutinho/concurrent-generic-heap/heap"
"github.com/guilhermeCoutinho/concurrent-generic-heap/safeheap"
)
func main() {
exampleHeapSafe()
exampleHeapNotSafe()
}
func exampleHeapSafe() {
minHeapUnsafe := heap.NewHeap(10, func(a, b interface{}) bool {
return a.(int) < b.(int)
})
minHeapSafe := safeheap.NewSafeHeap(minHeapUnsafe, 100)
doRandomConcurrentOperations(minHeapSafe)
fmt.Println(minHeapSafe.TestIfHeapified())
}
func exampleHeapNotSafe() {
minHeap := heap.NewHeap(10, func(a, b interface{}) bool {
return a.(int) < b.(int)
})
maxHeap := heap.NewHeap(10, func(a, b interface{}) bool {
return a.(int) > b.(int)
})
stringHeap := heap.NewHeap(10, func(a, b interface{}) bool {
return a.(string) > b.(string)
})
for i := 0; i < 10; i++ {
minHeap.Push(rand.Intn(100))
maxHeap.Push(rand.Intn(100))
stringHeap.Push(randomWord())
}
fmt.Println(minHeap.TestIfHeapified())
fmt.Println(maxHeap.TestIfHeapified())
fmt.Println(stringHeap.TestIfHeapified())
}
func doRandomConcurrentOperations(heap safeheap.SafeHeap) {
var wg sync.WaitGroup
goRoutines := 100
wg.Add(goRoutines)
for i := 0; i < goRoutines; i++ {
go func() {
defer wg.Done()
for j := 0; j < 1000; j++ {
heap.Push(rand.Intn(1000))
if rand.Intn(100) < 50 {
heap.Pop()
}
randomNumber := rand.Intn(1000)
heap.Remove(randomNumber)
}
}()
}
wg.Wait()
}