前进!前进!!不择手段的前进!
题目描述:
启动两个线程, 一个输出 1,3,5,7…99, 另一个输出 2,4,6,8…100 最后 STDOUT 中按序输出 1,2,3,4,5…100?
使用channel:
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
|
package main
import (
"fmt"
)
func f0(nums int, ch chan int, ch2 chan int) {
for i := nums; i <= 100; i += 2 {
if i == 0 {
fmt.Printf("%d ", i)
ch2 <- 1
continue
}
<-ch2
fmt.Printf("%d ", i)
ch2 <- 1
}
ch <- 1
}
func f1(nums int, ch chan int, ch2 chan int) {
for i := nums; i <= 100; i += 2 {
<-ch2
fmt.Printf("%d ", i)
ch2 <- 1
}
ch <- 1
}
func main() {
ch0 := make(chan int, 1)
ch1 := make(chan int, 1)
ch2 := make(chan int, 1)
go f0(0, ch0, ch2)
go f1(1, ch1, ch2)
<-ch0
<-ch1
}
|
用sync.Cond实现:
适用场景:多个goroutines等待,1个goroutine通知事件发生。
sync.Cond的定义和成员函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
type Cond struct {
// L is held while observing or changing the condition
L Locker
// contains filtered or unexported fields
}
//创建一个带锁的条件变量,Locker 通常是一个 *Mutex 或 *RWMutex
func NewCond(l Locker) *Cond
//唤醒所有因等待条件变量 c 阻塞的 goroutine
func (c *Cond) Broadcast()
//唤醒一个因等待条件变量 c 阻塞的 goroutine
func (c *Cond) Signal()
//自动解锁 c.L 并挂起 goroutine。只有当被 Broadcast 和 Signal 唤醒,Wait 才能返回,返回前会锁定 c.L
func (c *Cond) Wait()
|
- 可以将
wait() 和 signal() 理解成java中的wait() 和 notify()
- 只不过要配合mutex使用
实例:
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
|
package dtest
import (
"fmt"
"sync"
"testing"
)
var (
wg = sync.WaitGroup{}
mu = &sync.Mutex{}
cond1 = sync.NewCond(mu)
cond2 = sync.NewCond(mu)
)
func TestT(t *testing.T) {
wg.Add(2)
go thread1()
go thread2()
wg.Wait()
fmt.Println("end")
}
func thread1() {
for i := 1; i <= 100; i += 2 {
mu.Lock() //获取锁
if i != 1 {
cond1.Wait() //等待通知 挂起线程
}
fmt.Println("thread1 ->", i)
mu.Unlock()
cond2.Broadcast() //通知
}
wg.Done()
}
func thread2() {
for i := 2; i <= 100; i += 2 {
mu.Lock()
cond2.Wait()
fmt.Println("thread2 ->", i)
mu.Unlock()
cond1.Broadcast()
}
wg.Done()
}
|