Skip to content

Commit

Permalink
feat: add other-graceful
Browse files Browse the repository at this point in the history
  • Loading branch information
Yu-Jack committed Sep 5, 2022
1 parent 5dd9b47 commit 5561c4b
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 1 deletion.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,10 @@
| 1 | [Generator](./01-generator) |
| 2 | [Fan-In](./02-fan-in) |
| 3 | [Fan-Out](./03-fan-out) |
| 4 | [Fan-In and Fan-Out](./04-fan-in-fan-out) |
| 4 | [Fan-In and Fan-Out](./04-fan-in-fan-out) |

# 其他相關使用

| Number | Name |
|--------|------------------------------------------|
| 1 | [Graceful Shutdown](./other/01-graceful) |
10 changes: 10 additions & 0 deletions other/01-graceful/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Graceful Shutdown

通常應用程式在接受到 `kill -9` `kill -15` 等等相關訊號會直接關閉,但是實際上可以透過程式去處理取得這些 `signal` 時,要怎麼安全地關閉應用程式。


參考 [Graceful Shutdown Example Code](./main.go)

在範例程式中,可以試著換成 `newNormalContext`,並且在印出 0 的時候去中斷程式,會看到使用 `newNormalContext` 時並不會看到 1 被印出來,就意外的被中斷。

但是當使用 `newGracefulContext` 接收 signal 的情況下,可以做一些後續收尾的動作。所以用這個 `newGracefulContext` 看到 0 的時候去中斷程式,會看到 1 被印出來。
66 changes: 66 additions & 0 deletions other/01-graceful/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"time"
)

func newNormalContext() context.Context {
return context.Background()
}

func newGracefulContext() context.Context {
ctx, cancel := context.WithCancel(context.Background())

go func() {
sig := make(chan os.Signal)
signal.Notify(sig) // accept all signal
defer signal.Stop(sig)

select {
case <-ctx.Done():
case <-sig:
cancel()
}

fmt.Println("graceful shutdown")
}()

return ctx
}

func main() {
wg := sync.WaitGroup{}
wg.Add(1)

ctx := newGracefulContext()
//ctx := newNormalContext()
go func(ctx context.Context) {
defer wg.Done()

data := 0
fmt.Println(data)

// simulate the hard work, then set data of 1
time.Sleep(2 * time.Second)
data = 1
fmt.Println(data)

select {
case <-ctx.Done():
fmt.Println("skip following job")
return
default:
}

time.Sleep(2 * time.Second)
data = 2
fmt.Println(data)
}(ctx)

wg.Wait()
}

0 comments on commit 5561c4b

Please sign in to comment.