Skip to content

Commit 5bd2121

Browse files
committed
life is a race
1 parent 377c044 commit 5bd2121

File tree

2 files changed

+48
-4
lines changed

2 files changed

+48
-4
lines changed

day07-goroutines-channels-1/goroutines.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,14 @@ import (
66
"time"
77
)
88

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

1014
func sayMyName(name string){
1115
for i:=0; i<5; i++ {
12-
runtime.Gosched()
16+
runtime.Gosched() //Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.
1317
fmt.Println("Oh na na what's my name? ", name)
1418
time.Sleep(100*time.Millisecond) //doing some fake work here... please wait ZzzZzzZzzz
1519
}
@@ -18,7 +22,6 @@ func sayMyName(name string){
1822

1923
func main() {
2024

21-
runtime.GOMAXPROCS(runtime.NumCPU())
2225

2326
fmt.Println("You've got", runtime.NumCPU() , " CPU cores yo!")
2427

@@ -32,7 +35,7 @@ func main() {
3235

3336
go sayMyName("bbbbbbbbbb")
3437

35-
var input string
36-
fmt.Scanln(&input)
38+
// var input string
39+
// fmt.Scanln(&input)
3740
fmt.Println("ok dude! the show is over, go home and eat a potato")
3841
}

day07-goroutines-channels-1/race.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"sync"
6+
"runtime"
7+
"time"
8+
"math/rand"
9+
)
10+
11+
12+
13+
func init() {
14+
runtime.GOMAXPROCS(runtime.NumCPU())
15+
}
16+
17+
18+
19+
var globalcounter int
20+
var wg sync.WaitGroup
21+
22+
func main() {
23+
wg.Add(2)
24+
go incr("Red")
25+
go incr("Blue")
26+
wg.Wait()
27+
fmt.Println("Final counter:", globalcounter, "instead of 100")
28+
}
29+
30+
func incr(s string) {
31+
for i := 0; i < 50; i++ {
32+
x:=globalcounter
33+
x++
34+
time.Sleep(time.Duration(rand.Intn(2))*time.Millisecond)
35+
globalcounter = x
36+
fmt.Println(s, i, "counter:", globalcounter)
37+
}
38+
wg.Done()
39+
}
40+
41+

0 commit comments

Comments
 (0)