我有一个go函数,它会在Channel收到一些逻辑之后做一些逻辑.
我的问题是我希望函数在完成逻辑后保持活跃.我的想法是
我将在函数中添加无限循环.但是,我想知道这是不是
一个好的技术.我的守则如下:
func process(channel chan string, sid string) {
inputSid := <-channel
// check if sid exist in process pool
if strings.EqualFold(sid, inputSid) {
fmt.Println("Got message", sid)
//the code that I added to make this function alive
for {}
} else {
channel <- sid
//the code that I added to make this function alive
for {}
}
}
Run Code Online (Sandbox Code Playgroud)
备查:
保持函数活动的更好方法是使用一个空select语句,它将无限期地阻塞Go例程.与空for语句相反,它不会消耗CPU时间.
select { }
Run Code Online (Sandbox Code Playgroud)
只需使用标准的"Go way"即可.您可以range通过频道关闭它:
for sid := range channel {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
它将一直持续到通道关闭.添加这样的"等待循环"就是在寻找麻烦.