Created
June 9, 2019 15:46
-
-
Save romanitalian/e05821a66c89c0e6f91a147ad3bdc0aa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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