Skip to content

Instantly share code, notes, and snippets.

@gnufied
Created April 7, 2016 23:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnufied/402523b0601f008beb8d627899c73ef8 to your computer and use it in GitHub Desktop.
Save gnufied/402523b0601f008beb8d627899c73ef8 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
// DockerStats contains docker stats
type DockerStats struct {
previousCPUValues map[string]CPUValues
age int
}
// CPUValues struct contains the last cpu-usage values in order to compute properly the current values.
// (see calculateCPUPercent() for more details)
type CPUValues struct {
totCPU, systemCPU uint64
}
func (d DockerStats) getContainerStats(container string) {
fmt.Println("Getting container stats")
oldValue := d.previousCPUValues[container]
time.Sleep(time.Duration(80) * time.Millisecond)
cpuvalue := CPUValues{totCPU: 100 + oldValue.totCPU, systemCPU: 222 + oldValue.systemCPU}
time.Sleep(time.Duration(80) * time.Millisecond)
d.previousCPUValues[container] = cpuvalue
time.Sleep(time.Duration(80) * time.Millisecond)
d.age = 20
}
func main() {
d := new(DockerStats)
d.previousCPUValues = map[string]CPUValues{}
cpuvalue := CPUValues{totCPU: 45, systemCPU: 60}
d.previousCPUValues["foobar"] = cpuvalue
d.age = 100
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
container := fmt.Sprintf("foobar : %d", i)
d.previousCPUValues[container] = cpuvalue
go func() {
defer wg.Done()
d.getContainerStats(container)
}()
}
wg.Wait()
fmt.Println("totCPU", d.previousCPUValues["foobar"].totCPU)
fmt.Println("age", d.age)
}
@gnufied
Copy link
Author

gnufied commented Apr 7, 2016

It crashes with:

Getting container stats
Getting container stats
Getting container stats
Getting container stats
fatal error: concurrent map writes

goroutine 73 [running]:
runtime.throw(0x514040, 0x15)
        /data/go/src/runtime/panic.go:530 +0x90 fp=0xc820102e10 sp=0xc820102df8
runtime.mapassign1(0x4b9d40, 0xc82000e450, 0xc820102f48, 0xc820102f08)
        /data/go/src/runtime/hashmap.go:445 +0xb1 fp=0xc820102eb8 sp=0xc820102e10
main.DockerStats.getContainerStats(0xc82000e450, 0x64, 0x4ff0e0, 0x6)
        /home/hulk/snippets/golang/using_map.go:27 +0x200 fp=0xc820102f78 sp=0xc820102eb8
main.main.func1(0xc82000a480, 0xc82000a430)
        /home/hulk/snippets/golang/using_map.go:47 +0x69 fp=0xc820102fa0 sp=0xc820102f78
runtime.goexit()
        /data/go/src/runtime/asm_amd64.s:1998 +0x1 fp=0xc820102fa8 sp=0xc820102fa0
created by main.main
        /home/hulk/snippets/golang/using_map.go:48 +0x46d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment