-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrency.go
61 lines (51 loc) · 892 Bytes
/
concurrency.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
package main
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
)
var wg sync.WaitGroup
var counter int64
//var mutex sync.Mutex
func concurrency(){ // using wg
wg.Add(2)
go incrementer("foo:")
go incrementer("bar:")
wg.Wait()
}
func incrementer(s string){
for i:=0; i<20; i++{
time.Sleep(time.Duration(rand.Intn(3))*time.Millisecond)
atomic.AddInt64(&counter, 1)
fmt.Println(s, i, "counter", counter)
}
wg.Done()
}
/** using mutex
func incrementer(s string){
for i:=0; i<20; i++{
time.Sleep(time.Duration(rand.Intn(3))*time.Millisecond)
mutex.Lock()
counter++
fmt.Println(s, i, "counter", counter)
mutex.Unlock()
}
wg.Done()
}
*/
func foo(){
for i:=0; i<10;i++{
fmt.Println("foo", i)
time.Sleep(3 * time.Millisecond)
}
wg.Done()
}
func bar() {
for i:=0; i<10;i++{
fmt.Println("bar", i)
time.Sleep(3 * time.Millisecond)
}
wg.Done()
}