Skip to content

Instantly share code, notes, and snippets.

@jasonkeene
Created May 14, 2017 16:26
Show Gist options
  • Select an option

  • Save jasonkeene/cad0d9454598c3a9c941463bcfbc5a8a to your computer and use it in GitHub Desktop.

Select an option

Save jasonkeene/cad0d9454598c3a9c941463bcfbc5a8a to your computer and use it in GitHub Desktop.
A demo program to experiment with tracing Go programs on linux.
// This program atomically increments two unit64 values and prints them out
// periodically.
//
// The objective is to capture the same data `stat()` is providing by
// instrumenting calls to `read()` and `write()`.
package main
import (
"log"
"sync/atomic"
"time"
)
type foo struct {
r uint64 // fake read head
w uint64 // fake write head
}
// read moves a fake read head.
func (f *foo) read() {
atomic.AddUint64(&f.r, 1)
}
// write moves a fake write head.
func (f *foo) write() {
atomic.AddUint64(&f.w, 1)
}
// stat reads both heads. The entire operaton is not atomic as writes can
// occur inbetween the independent reads of the heads.
func (f *foo) stat() (uint64, uint64) {
return atomic.LoadUint64(&f.r), atomic.LoadUint64(&f.w)
}
func main() {
f := &foo{}
go func() {
for {
f.read()
}
}()
go func() {
for {
f.write()
}
}()
for {
r, w := f.stat()
log.Printf("r: %d, w: %d", r, w)
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment