Created
June 9, 2019 15:45
-
-
Save romanitalian/e16e405fcf1fe636c7b4de76c7ab238f 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" | |
"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