File tree Expand file tree Collapse file tree 2 files changed +61
-1
lines changed Expand file tree Collapse file tree 2 files changed +61
-1
lines changed Original file line number Diff line number Diff line change 1
1
``` 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
3
29
```
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 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
+
3
27
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
+ }
4
36
37
+ quit <- "Stop baking"
38
+ fmt .Println ("Final Message:" , <- quit )
5
39
}
You can’t perform that action at this time.
0 commit comments