两道关于 golang race 的题目
2024-02-26 15:13:18

逛 Twitter 的时候看到了别人发的两道题目,考察 Golang 中并发代码的编写,感觉挺有意思的,记录一下。

题目一

这道题要用到 go 关键字实现并发才能完成,同时为了获取到 slow 是否结束,那么我们就需要有一个通知的机制,这需要使用到 channel 来解决。
最后给出的答案,正好也就这么几行,使用了 go func(){}() 和 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
41
42
package main

import (
"context"
"fmt"
"math/rand"
"time"
)

// 1、只能编辑 foo 函数
// 2、foo 必须要调用 slow 函数
// 3、foo 函数在 ctx 超时后必须立刻返回
// 4、如果 slow 结束的比 ctx 快,也立刻返回

func main() {
rand.Seed(time.Now().UnixNano())
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()

foo(ctx)
}

func foo(ctx context.Context) {
ch := make(chan int)

go func() {
slow()
ch <- 1
}()
select {
case <-ctx.Done():
case <-ch:
}
}

func slow() {
n := rand.Intn(3)
fmt.Printf("sleep %d\n", n)
time.Sleep(time.Duration(n) * time.Second)
}

题目二

这道题也类似于第一题,不过变成了三个函数,谁先执行完毕程序就会退出。使用 ctx 配合 go func(),很巧妙的就完成了,牛蛙牛蛙。

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
package main

import (
"context"
"time"
)

var (
f1 = func() { time.Sleep(time.Microsecond) }
f2 = func() { time.Sleep(time.Second) }
f3 = func() { time.Sleep(time.Minute) }
)

func main() {
race(f1, f2, f3)
}

// race run all funcs, return when the first one finished
func race(funcs ...func()) {
ctx, cancel := context.WithCancel(context.Background())

for _, f := range funcs {
go func(f func()) {
f()
cancel()
}(f)
}
<-ctx.Done()
}