Files
  • main.go
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
package main

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

// :show start
var cache map[int]int
var mu sync.RWMutex

func expensiveOperation(n int) int {
	// in real code this operation would be very expensive
	return n * n
}

func getCached(n int) int {
	mu.RLock()
	v, isCached := cache[n]
	mu.RUnlock()
	if isCached {
		return v
	}

	v = expensiveOperation(n)

	mu.Lock()
	cache[n] = v
	mu.Unlock()
	return v
}

func accessCache() {
	total := 0
	for i := 0; i < 5; i++ {
		n := getCached(i)
		total += n
	}
	fmt.Printf("total: %d\n", total)
}

// :show end

func main() {
	// :show start
	cache = make(map[int]int)
	go accessCache()
	accessCache()
	// :show end

	// for simplicity of the example
	// don't use time.Sleep() to coordinate goroutines
	// in production code
	time.Sleep(100 * time.Millisecond)
}