File tree Expand file tree Collapse file tree 2 files changed +47
-12
lines changed Expand file tree Collapse file tree 2 files changed +47
-12
lines changed Original file line number Diff line number Diff line change 1
1
``` mermaid
2
2
sequenceDiagram
3
3
participant M as Main
4
- participant S as Select Statement
4
+ participant S as Sender(goroutine)
5
5
participant C as Channel
6
- participant T as Timer
7
-
8
- M->>S: Start select
9
- S->>C: Try receive
10
- S->>T: Start timer
11
- alt Channel receives value
12
- C-->>S: Value received
13
- S-->>M: Return value
14
- else Timer expires
15
- T-->>S: Timeout
16
- S-->>M: Return timeout error
6
+ participant T as Time.After
7
+
8
+ M->>S: Start sender goroutine
9
+ activate S
10
+ S-->>M: Return channel
11
+
12
+ loop Until timeout
13
+ S->>C: Send message (i)
14
+ S->>S: Sleep random time
15
+ alt Message Available
16
+ C->>M: Receive message
17
+ M->>M: Print message
18
+ else 5s Timeout
19
+ T->>M: Timeout signal
20
+ M->>M: Print "no response"
21
+ M->>M: return
22
+ end
17
23
end
18
24
```
Original file line number Diff line number Diff line change 1
1
package main
2
2
3
+ import (
4
+ "fmt"
5
+ "math/rand"
6
+ "time"
7
+ )
8
+
9
+ func sender (message string ) <- chan string {
10
+ c := make (chan string )
11
+ go func () {
12
+ for i := 0 ; ; i ++ {
13
+ c <- fmt .Sprintf ("%s = %d" , message , i )
14
+ time .Sleep (time .Duration (rand .Intn (1000 )) * time .Millisecond )
15
+ }
16
+ }()
17
+
18
+ return c
19
+ }
20
+
3
21
func main () {
22
+ c := sender ("Test" )
4
23
24
+ timeout := time .After (5 * time .Second )
25
+ for {
26
+ select {
27
+ case str := <- c :
28
+ fmt .Println (str )
29
+ case <- timeout :
30
+ fmt .Println ("no response..." )
31
+ return
32
+ }
33
+ }
5
34
}
You can’t perform that action at this time.
0 commit comments