Skip to content

Instantly share code, notes, and snippets.

@romanitalian
Created June 9, 2019 15:45
Show Gist options
  • Save romanitalian/e16e405fcf1fe636c7b4de76c7ab238f to your computer and use it in GitHub Desktop.
Save romanitalian/e16e405fcf1fe636c7b4de76c7ab238f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
type atomicCounter struct {
val int64
}
func (c *atomicCounter) Add(x int64) {
atomic.AddInt64(&c.val, x)
runtime.Gosched()
}
func (c *atomicCounter) Value() int64 {
return atomic.LoadInt64(&c.val)
}
func main() {
counter := atomicCounter{}
counter = process(counter)
// time.Sleep(time.Second)
fmt.Println(counter.Value())
}
func process(counter atomicCounter) atomicCounter {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 2; j++ {
counter.Add(1)
}
}()
}
wg.Wait()
return counter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment