Skip to content

Commit 64abaaf

Browse files
committedNov 27, 2024
update
1 parent 930a2de commit 64abaaf

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed
 

‎07-quit-signal/README.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,29 @@
11
```mermaid
2-
2+
sequenceDiagram
3+
participant M as Main
4+
participant B as Baker Goroutine
5+
participant C as Cake Channel
6+
participant Q as Quit Channel
7+
8+
Note over M,B: Setup Phase
9+
M->>B: Create baker goroutine
10+
B->>C: Create cake channel
11+
12+
Note over M,B: Baking Phase
13+
rect rgb(240, 240, 240)
14+
loop 5 times
15+
B->>C: Send cake ready message
16+
C->>M: Receive cake message
17+
Note over B: Random sleep (200-1000ms)
18+
end
19+
end
20+
21+
Note over M,B: Cleanup Phase
22+
M->>Q: Send "Stop baking"
23+
Q->>B: Receive quit signal
24+
B->>Q: Send cleanup confirmation
25+
Q->>M: Receive final message
26+
27+
Note over B: Goroutine exits
28+
Note over C: Channel closes
329
```

‎07-quit-signal/main.go

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

3+
import (
4+
"fmt"
5+
"math/rand"
6+
"time"
7+
)
8+
9+
func baker(name string, quit chan string, r *rand.Rand) <-chan string {
10+
c := make(chan string)
11+
go func() {
12+
defer close(c)
13+
for i := 1; ; i++ {
14+
select {
15+
case c <- fmt.Sprintf("%s: Cake #%d is ready!", name, i):
16+
case message := <-quit:
17+
fmt.Printf("[%s] Stopping work: %s. Cleaning up...\n", name, message)
18+
quit <- fmt.Sprintf("%s: All baking equipment is cleaned up. Goodbye!", name)
19+
return
20+
}
21+
time.Sleep(time.Duration(r.Intn(800)+200) * time.Millisecond)
22+
}
23+
}()
24+
return c
25+
}
26+
327
func main() {
28+
r := rand.New(rand.NewSource(time.Now().UnixNano()))
29+
30+
quit := make(chan string)
31+
bakery := baker("Chef Paul", quit, r)
32+
33+
for i := 0; i < 5; i++ {
34+
fmt.Println(<-bakery)
35+
}
436

37+
quit <- "Stop baking"
38+
fmt.Println("Final Message:", <-quit)
539
}

0 commit comments

Comments
 (0)
Please sign in to comment.