Skip to content

Instantly share code, notes, and snippets.

@romanitalian
Created June 9, 2019 15:46
Show Gist options
  • Save romanitalian/e05821a66c89c0e6f91a147ad3bdc0aa to your computer and use it in GitHub Desktop.
Save romanitalian/e05821a66c89c0e6f91a147ad3bdc0aa to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
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{}
counter = process(mutexCounter{})
fmt.Println(counter.Value())
}
func process(counter mutexCounter) mutexCounter {
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