|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strconv" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +// EXERCISE: |
| 11 | +// Find what's wrong in the following code |
| 12 | +// Make sure all the tests are passing |
| 13 | +// DO NOT remove any Sleep() calls |
| 14 | + |
| 15 | +// try running this with the -race flag |
| 16 | +// go run -race exercise.go |
| 17 | + |
| 18 | +// run the tests using: |
| 19 | +// GOFLAGS="-count=1" go test . |
| 20 | +func main() { |
| 21 | + c := &catalog{data: map[string]string{ |
| 22 | + "p1": "apples", |
| 23 | + "p2": "oranges", |
| 24 | + "p3": "grapes", |
| 25 | + "p4": "pineapple", |
| 26 | + "p5": "bananas", |
| 27 | + }} |
| 28 | + |
| 29 | + now := time.Now() |
| 30 | + exercise(c, "p1", "p2", "p3", "p4", "p5") |
| 31 | + fmt.Println("elapsed:", time.Since(now)) |
| 32 | +} |
| 33 | + |
| 34 | +func exercise(c *catalog, ids ...string) { |
| 35 | + var wg sync.WaitGroup |
| 36 | + wg.Add(1000) |
| 37 | + |
| 38 | + for i := 0; i < 1000; i++ { |
| 39 | + go func(i int) { |
| 40 | + defer wg.Done() |
| 41 | + for _, id := range ids { |
| 42 | + c.get(id) |
| 43 | + } |
| 44 | + c.add("generated_"+strconv.Itoa(i), "generated product") |
| 45 | + }(i+1) |
| 46 | + } |
| 47 | + |
| 48 | + wg.Wait() |
| 49 | +} |
| 50 | + |
| 51 | +type catalog struct { |
| 52 | + mu sync.Mutex |
| 53 | + data map[string]string |
| 54 | +} |
| 55 | + |
| 56 | +func (c *catalog) add(id, product string) { |
| 57 | + c.mu.Lock() |
| 58 | + defer c.mu.Unlock() |
| 59 | + // simulate load |
| 60 | + time.Sleep(500*time.Nanosecond) |
| 61 | + c.data[id] = product |
| 62 | +} |
| 63 | + |
| 64 | +func (c *catalog) get(id string) string { |
| 65 | + c.mu.Lock() |
| 66 | + defer c.mu.Unlock() |
| 67 | + // simulate load |
| 68 | + time.Sleep(500*time.Nanosecond) |
| 69 | + // avoid key existence check |
| 70 | + return c.data[id] |
| 71 | +} |
0 commit comments