我有一個cleanUp洗掉過時檔案的后臺任務 ( )。
func main() {
// 4 procs/childs max
runtime.GOMAXPROCS(4)
// start a cleanup cron-job
go cleanUp()
app := fiber.New(fiber.Config{
Prefork: true,
})
app.Post("/", handleFileupload)
log.Fatal(app.Listen(":4000"))
}
func cleanUp() {
fmt.Println("Cleaning Up..")
for {
// deletes old files here
time.Sleep(60 * time.Second)
}
}
目前cleanUp在所有 4 個行程上運行并列印Cleaning Up..4 次。
但我希望它只在一個行程上運行并列印一個Cleaning Up... 我嘗試過 waitGroups 和頻道,但未能實作我想要的。
如何僅在單個行程上運行它以避免競爭條件?
這是輸出:
Cleaning Up..
┌───────────────────────────────────────────────────┐ ┌───────────────────────────────────────────────────┐
│ Fiber v2.38.1 │ │ Child PIDs ... 79378, 79379, 79380, 79381 │
│ http://127.0.0.1:4000 │ └───────────────────────────────────────────────────┘
│ (bound on host 0.0.0.0 and port 4000) │
│ │
│ Handlers ............. 5 Processes ........... 4 │
│ Prefork ........ Enabled PID ............. 79377 │
└───────────────────────────────────────────────────┘
Cleaning Up..
Cleaning Up..
Cleaning Up..
Cleaning Up..
uj5u.com熱心網友回復:
Fiber 產生了幾個行程來處理傳入的請求。您需要的是在主行程中啟動清理例程并在子行程中跳過它。
光纖提供fiber.IsChild功能:
// start a cleanup cron-job
if !fiber.IsChild() {
go cleanUp()
}
我稍微修改了您的示例以在處理程式和清理 goroutine 中列印行程 ID:
func main() {
// 4 procs/childs max
runtime.GOMAXPROCS(4)
// start a cleanup cron-job
if !fiber.IsChild() {
go cleanUp()
}
app := fiber.New(fiber.Config{
Prefork: true,
})
app.Post("/", handleFileupload)
log.Fatal(app.Listen(":4000"))
}
func cleanUp() {
fmt.Println("Cleaning Up.. Pid:", syscall.Getpid())
for {
// deletes old files here
time.Sleep(1 * time.Second)
fmt.Println("Cleaning Up.. Pid:", syscall.Getpid())
}
}
func handleFileupload(ctx *fiber.Ctx) error {
println("Upload: pid ", syscall.Getpid())
return nil
}
結果:
Cleaning Up.. Pid: 27035
┌───────────────────────────────────────────────────┐ ┌───────────────────────────────────────────────────┐
│ Fiber v2.39.0 │ │ Child PIDs ... 27041, 27042, 27044, 27045 │
│ http://127.0.0.1:4000 │ └───────────────────────────────────────────────────┘
│ (bound on host 0.0.0.0 and port 4000) │
│ │
│ Handlers ............. 1 Processes ........... 4 │
│ Prefork ........ Enabled PID ............. 27035 │
└───────────────────────────────────────────────────┘
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
如您所見,清理僅在主行程中運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520332.html
標籤:去光纤
