@kjk1/

gobook rwmutex

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.12513104835929667","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJzeW5jIgoJInRpbWUiCikKCi8vIDpzaG93IHN0YXJ0CnZhciBjYWNoZSBtYXBbaW50XWludAp2YXIgbXUgc3luYy5SV011dGV4CgpmdW5jIGV4cGVuc2l2ZU9wZXJhdGlvbihuIGludCkgaW50IHsKCS8vIGluIHJlYWwgY29kZSB0aGlzIG9wZXJhdGlvbiB3b3VsZCBiZSB2ZXJ5IGV4cGVuc2l2ZQoJcmV0dXJuIG4gKiBuCn0KCmZ1bmMgZ2V0Q2FjaGVkKG4gaW50KSBpbnQgewoJbXUuUkxvY2soKQoJdiwgaXNDYWNoZWQgOj0gY2FjaGVbbl0KCW11LlJVbmxvY2soKQoJaWYgaXNDYWNoZWQgewoJCXJldHVybiB2Cgl9CgoJdiA9IGV4cGVuc2l2ZU9wZXJhdGlvbihuKQoKCW11LkxvY2soKQoJY2FjaGVbbl0gPSB2CgltdS5VbmxvY2soKQoJcmV0dXJuIHYKfQoKZnVuYyBhY2Nlc3NDYWNoZSgpIHsKCXRvdGFsIDo9IDAKCWZvciBpIDo9IDA7IGkgPCA1OyBpKysgewoJCW4gOj0gZ2V0Q2FjaGVkKGkpCgkJdG90YWwgKz0gbgoJfQoJZm10LlByaW50ZigidG90YWw6ICVkXG4iLCB0b3RhbCkKfQoKLy8gOnNob3cgZW5kCgpmdW5jIG1haW4oKSB7CgkvLyA6c2hvdyBzdGFydAoJY2FjaGUgPSBtYWtlKG1hcFtpbnRdaW50KQoJZ28gYWNjZXNzQ2FjaGUoKQoJYWNjZXNzQ2FjaGUoKQoJLy8gOnNob3cgZW5kCgoJLy8gZm9yIHNpbXBsaWNpdHkgb2YgdGhlIGV4YW1wbGUKCS8vIGRvbid0IHVzZSB0aW1lLlNsZWVwKCkgdG8gY29vcmRpbmF0ZSBnb3JvdXRpbmVzCgkvLyBpbiBwcm9kdWN0aW9uIGNvZGUKCXRpbWUuU2xlZXAoMTAwICogdGltZS5NaWxsaXNlY29uZCkKfQ=="},"asBuffer":null},"loaded":true}}
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)
}