Skip to content

Commit 331ddd2

Browse files
committed
Condition
1 parent ee68ebd commit 331ddd2

File tree

3 files changed

+95
-0
lines changed

3 files changed

+95
-0
lines changed

15-Concurrency/06-Cond/example1.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package main
2+
3+
import (
4+
"log"
5+
"sync"
6+
"time"
7+
)
8+
9+
var myList = []int{}
10+
var done = false
11+
12+
func read(name string, c *sync.Cond) {
13+
defer c.L.Unlock()
14+
c.L.Lock()
15+
if !done {
16+
c.Wait()
17+
}
18+
log.Println(name, "starts reading")
19+
}
20+
21+
func write(id int, c *sync.Cond) {
22+
log.Println(id, "starts writing")
23+
time.Sleep(time.Second)
24+
c.L.Lock()
25+
myList = append(myList, id)
26+
if len(myList) == 100 {
27+
done = true
28+
c.Broadcast()
29+
log.Println(id, "wakes all")
30+
}
31+
c.L.Unlock()
32+
}
33+
34+
func RunExample1() {
35+
cond := sync.NewCond(&sync.Mutex{})
36+
37+
go read("reader1", cond)
38+
go read("reader2", cond)
39+
go read("reader3", cond)
40+
for i := 0; i < 1000; i++ {
41+
write(i, cond)
42+
}
43+
44+
time.Sleep(time.Second * 3)
45+
}
46+
47+
//

15-Concurrency/06-Cond/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module condExample
2+
3+
go 1.18

15-Concurrency/06-Cond/main.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package main
2+
3+
import (
4+
"sync"
5+
"time"
6+
)
7+
8+
var userList = []int{}
9+
var ready = false
10+
11+
func main() {
12+
13+
condition := sync.NewCond(&sync.Mutex{})
14+
15+
for i := 0; i < 1000; i++ {
16+
go NewRequest(i, condition)
17+
}
18+
19+
time.Sleep(time.Second * 5)
20+
21+
}
22+
23+
func NewRequest(userId int, condition *sync.Cond) {
24+
Checking(userId, condition)
25+
condition.L.Lock()
26+
defer condition.L.Unlock()
27+
for !ready {
28+
condition.Wait()
29+
}
30+
println("User ", userId, "start streaming") //
31+
}
32+
33+
func Checking(userId int, condition *sync.Cond) {
34+
println(userId, "waiting for start streaming")
35+
time.Sleep(time.Millisecond * 50)
36+
condition.L.Lock()
37+
defer condition.L.Unlock()
38+
userList = append(userList, userId)
39+
if len(userList) == 55 {
40+
ready = true
41+
condition.Broadcast()
42+
println("User ", userId, "waiting end")
43+
}
44+
45+
}

0 commit comments

Comments
 (0)