-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync.go
62 lines (53 loc) · 1006 Bytes
/
sync.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package concur
/*
This Program demostrates changing a shared variable in runtime,
and protecting it with the help of MutexLock
*/
import (
"fmt"
"sync"
)
var (
counter int
mu sync.RWMutex
)
func Increment(wg *sync.WaitGroup) {
defer wg.Done()
mu.Lock()
counter++
fmt.Println("writing: ", counter)
mu.Unlock()
}
func Decrementer(wg *sync.WaitGroup) {
defer wg.Done()
mu.Lock()
counter--
fmt.Println("writing: ", counter)
mu.Unlock()
}
func ReadCounter(wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("read request")
fmt.Println(">reading: ", counter)
fmt.Println("read complete")
}
// Dispatch threads with waitgroup
func DispatchThreads() {
counter = 0
var reps = 10
var wg sync.WaitGroup
for i := 0; i < reps; i++ {
wg.Add(1)
go Increment(&wg)
wg.Add(1)
go ReadCounter(&wg)
}
wg.Wait()
fmt.Println(counter)
}
// func main() {
// start := time.Now()
// DispatchThreads()
// elapsed := time.Since(start)
// log.Printf("Binomial took %s", elapsed)
// }