Skip to content

Commit d4febc5

Browse files
committed
atomic
1 parent cee5685 commit d4febc5

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

day11-mutex-events-models-5/atomic.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
package main
3+
4+
import (
5+
"fmt"
6+
"sync"
7+
"sync/atomic"
8+
"runtime"
9+
//"math/rand"
10+
//"time"
11+
)
12+
13+
func init() {
14+
runtime.GOMAXPROCS(runtime.NumCPU())
15+
}
16+
17+
var count int64
18+
var wg sync.WaitGroup
19+
20+
func main() {
21+
wg.Add(2)
22+
go incrementor("1")
23+
go incrementor("2")
24+
wg.Wait()
25+
fmt.Println("Final Counter:", count)
26+
}
27+
28+
func incrementor(s string) {
29+
for i := 0; i < 10000; i++ {
30+
runtime.Gosched() //Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.
31+
//Alternative to Gosched() is //time.Sleep(time.Duration(rand.Intn(2))*time.Millisecond)
32+
33+
atomic.AddInt64(&count, 1)
34+
//count++
35+
36+
fmt.Println("Process: "+s+" printing:", i)
37+
}
38+
wg.Done()
39+
}

day11-mutex-events-models-5/mutex.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,17 @@ import (
66
"sync"
77
)
88

9+
func init() {
10+
runtime.GOMAXPROCS(runtime.NumCPU())
11+
}
12+
913
func main() {
1014

11-
runtime.GOMAXPROCS(4)
1215
mutex := new(sync.Mutex)
1316

14-
for i := 1; i < 10; i++ {
17+
for i := 0; i < 10; i++ {
1518
//fmt.Println(i)
16-
for j := 1; j < 10; j++ {
19+
for j := 0; j < 10; j++ {
1720
mutex.Lock()
1821
go func() {
1922
fmt.Printf("%d %d\n", i, j)

0 commit comments

Comments
 (0)