-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mutex.go
44 lines (34 loc) · 756 Bytes
/
Mutex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main
// Run -- go run -race Race.go
import (
"fmt"
"runtime"
"sync"
)
func main() {
fmt.Println("Number of CPUs:", runtime.NumCPU())
fmt.Println("Goroutines:", runtime.NumGoroutine())
counter := 0
const gs = 100
var wg sync.WaitGroup
wg.Add(gs)
var mu sync.Mutex
for i := 0; i < gs; i++ {
go func() {
mu.Lock()
v := counter
// Gosched yields the processor, allowing other goroutines to run.
// It does not suspend the current goroutine, so execution resumes
// automatically.
runtime.Gosched()
v++
counter = v
mu.Unlock()
wg.Done()
}()
fmt.Println("Goroutines:", runtime.NumGoroutine())
}
wg.Wait()
fmt.Println("Goroutines:", runtime.NumGoroutine())
fmt.Println("Count:", counter)
}