![](/img/trans.png)
[英]How can I have a single goroutine function that waits for values from multiple others?
[英]How can I stop the goroutine in the New Object?
代碼如下:
package main
import (
"time"
"runtime"
"runtime/debug"
)
type obj struct {
}
func getObj() *obj{
b := new(obj)
go func() {
i := 0
for {
println(i)
time.Sleep(time.Second)
i++
}
}()
return b
}
func main() {
b := getObj()
println(b)
time.Sleep(time.Duration(3)*time.Second)
b = nil
runtime.GC()
debug.FreeOSMemory()
println("before")
time.Sleep(time.Duration(10)*time.Second)
println("after")
}
我創建了一個obj,使用完之后,我想關閉obj中的goroutine,並刪除obj以釋放內存。 我嘗試了runtime.GC()
和debug.FreeOSMemory()
,但是它不起作用。
添加一個“完成”頻道。 goroutine在每次迭代時檢查通道,並在通道關閉時退出。 完成后,主goroutine將關閉通道。
type obj struct {
done chan struct{} // done is closed when goroutine should exit
}
func getObj() *obj {
b := &obj{done: make(chan struct{})}
go func() {
i := 0
for {
select {
case <-b.done:
// Channel was closed, exit the goroutine
return
default:
// Channel not closed, keep going
}
fmt.Println(i)
time.Sleep(time.Second)
i++
}
}()
return b
}
func main() {
b := getObj()
fmt.Println(b)
time.Sleep(time.Duration(3) * time.Second)
close(b.done) // Signal goroutine to exit
fmt.Println("before")
time.Sleep(time.Duration(10) * time.Second)
fmt.Println("after")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.