Skip to content

Instantly share code, notes, and snippets.

@romanitalian
Created April 26, 2018 19:33
Show Gist options
  • Save romanitalian/b5ce25421367b0dcb1d5d33b9f22447f to your computer and use it in GitHub Desktop.
Save romanitalian/b5ce25421367b0dcb1d5d33b9f22447f to your computer and use it in GitHub Desktop.
Why:
package main
import (
"sync"
"time"
"fmt"
)
type mutexCounter struct {
mu sync.Mutex
x int64
}
func (c *mutexCounter) Add(x int64) {
c.mu.Lock()
c.x += x
c.mu.Unlock()
}
func (c *mutexCounter) Value() (x int64) {
c.mu.Lock()
x = c.x
c.mu.Unlock()
return
}
func main() {
counter := mutexCounter{}
for i := 0; i < 100; i++ {
go func(no int) {
for i := 0; i < 10000; i++ {
counter.Add(1)
}
}(i)
}
time.Sleep(time.Second)
fmt.Println(counter.Value())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment