Skip to content

Instantly share code, notes, and snippets.

View ash2k's full-sized avatar

Mikhail Mazurskiy ash2k

View GitHub Profile
@ash2k
ash2k / Output
Created March 11, 2016 12:01
An example of racy map access pattern
$ go build --race ./main.go
$ ./main
5
==================
WARNING: DATA RACE
Read by goroutine 7:
runtime.mapaccess1_fast64()
/usr/local/Cellar/go/1.6/libexec/src/runtime/hashmap_fast.go:103 +0x0
main.main.func2()
/Users/ash2k/sources/gotest2/main.go:18 +0x4e
@ash2k
ash2k / Output
Created March 11, 2016 12:06
Safe concurrent reads
$ go build --race ./no_race.go
$ ./no_race
1
1
1
1
1
1
1
1
var sink string
var x string = "somestring"
// BenchmarkPrint-8 10000000 198 ns/op 32 B/op 2 allocs/op
func BenchmarkPrint(b *testing.B) {
b.ReportAllocs()
var s string
for i := 0; i < b.N; i++ {
s = fmt.Sprintf("abc.%s", x)
}
@ash2k
ash2k / shutdown.go
Last active February 14, 2018 20:11
Clean shutdown of Go http server
func startStopServer(ctx context.Context, srv *http.Server, shutdownTimeout time.Duration) error {
var wg sync.WaitGroup
defer wg.Wait() // wait for goroutine to shutdown active connections
ctx, cancel := context.WithCancel(ctx)
defer cancel()
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
c, cancel := context.WithTimeout(context.Background(), shutdownTimeout)