Go 管理后台操作(创建/终止)
我第一次在这里发帖,因为我在互联网上找不到一个干净的解决方案 我的目标很简单,我需要创建一个后台操作(goroutine或process或其他什么…),我可以正确地杀死(而不是留在后台) 我试过很多方法,比如使用chan或context 但我从来都找不到避免泄密的正确方法 以下是一个例子:Go 管理后台操作(创建/终止),go,concurrency,kill,Go,Concurrency,Kill,我第一次在这里发帖,因为我在互联网上找不到一个干净的解决方案 我的目标很简单,我需要创建一个后台操作(goroutine或process或其他什么…),我可以正确地杀死(而不是留在后台) 我试过很多方法,比如使用chan或context 但我从来都找不到避免泄密的正确方法 以下是一个例子: package main import ( "log" "strconv" "runtime" "time" "math/rand" ) func main() {
package main
import (
"log"
"strconv"
"runtime"
"time"
"math/rand"
)
func main() {
log.Println("goroutines: " + strconv.Itoa(runtime.NumGoroutine()))
func1()
leak := ""
if runtime.NumGoroutine() > 1 {
leak = " there is one LEAK !!"
}
log.Println("goroutines: " + strconv.Itoa(runtime.NumGoroutine()) + leak)
}
func func1() {
done := make(chan struct{})
quit := make(chan struct{})
go func() {
log.Println("goroutines: " + strconv.Itoa(runtime.NumGoroutine()))
select {
case <-quit:
log.Println("USEFUL ???")
return
default:
func2()
done<-struct{}{}
}
}()
select {
case <-time.After(4 * time.Second):
quit<-struct{}{}
log.Println("TIMEOUT")
case <-done:
log.Println("NO TIMEOUT")
}
}
func func2() {
log.Println("JOB START")
rand.Seed(time.Now().UnixNano())
val := rand.Intn(10)
log.Println("JOB DURATION: " + strconv.Itoa(val))
time.Sleep(time.Duration(val) * time.Second) // fake a long process with an unknown duration
log.Println("JOB DONE")
}
主程序包
进口(
“日志”
“strconv”
“运行时”
“时间”
“数学/兰德”
)
func main(){
log.Println(“goroutines:+strconv.Itoa(runtime.NumGoroutine()))
func1()
泄漏:=“”
如果runtime.NumGoroutine()大于1{
leak=“有一个漏洞!!”
}
log.Println(“goroutines:+strconv.Itoa(runtime.NumGoroutine())+leak)
}
func func1(){
完成:=make(chan结构{})
quit:=make(chan结构{})
go func(){
log.Println(“goroutines:+strconv.Itoa(runtime.NumGoroutine()))
挑选{
案例您的问题在于:
quit := make(chan struct{})
go func() {
for {
select {
case <-quit:
log.Println("USEFUL ???")
return
default:
func2()
quit<-struct{}{}
return
}
}
}()
quit:=make(chan结构{})
go func(){
为了{
挑选{
这个案例能回答你的问题吗?谢谢,我已经看到了这个线索;他们说杀死一个goroutine是不可能的;好吧,但这里只是一个例子,我不关心goroutine。就像我写的,我只想在Go中杀死一个后台操作,我不知道怎么做:)如果你有任何建议,谢谢你的回答;我有编辑了我的示例。我会记住分割通道以进行输入和输出通信(这里我用“完成”和“退出”进行了分割)。但我不知道即使我删除循环如何达到我的目标;如果你有任何线索,也可以杀死后台操作(goroutine、process或其他…)