Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 930a2de

Browse files
committedNov 25, 2024
update
1 parent a1c7ad3 commit 930a2de

File tree

2 files changed

+47
-12
lines changed

2 files changed

+47
-12
lines changed
 

‎06-select-timeout/README.md

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
11
```mermaid
22
sequenceDiagram
33
participant M as Main
4-
participant S as Select Statement
4+
participant S as Sender(goroutine)
55
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
1723
end
1824
```

‎06-select-timeout/main.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,34 @@
11
package main
22

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+
321
func main() {
22+
c := sender("Test")
423

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+
}
534
}

0 commit comments

Comments
 (0)
Please sign in to comment.