Multithreading 如何在新对象中停止goroutine?

Multithreading 如何在新对象中停止goroutine?,multithreading,go,parallel-processing,goroutine,Multithreading,Go,Parallel Processing,Goroutine,代码如下: 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)

代码如下:

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")
}
类型对象结构{
当goroutine应该退出时,done chan struct{}//done关闭
}
func getObj()*obj{
b:=&obj{done:make(chan struct{}}
go func(){
i:=0
为了{
挑选{
case添加一个“完成”通道。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")
}
类型对象结构{
当goroutine应该退出时,done chan struct{}//done关闭
}
func getObj()*obj{
b:=&obj{done:make(chan struct{}}
go func(){
i:=0
为了{
挑选{
案例