Created
April 26, 2018 19:33
-
-
Save romanitalian/b5ce25421367b0dcb1d5d33b9f22447f to your computer and use it in GitHub Desktop.
Why:
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 ( | |
"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