猿问

我应该将请求对象传递给 goroutine 以阻止来自通道的 for-select 循环吗?

我在代码中有以下 for-select 结构:


go func(runCh chan Caller, shutdownSignal chan bool) {

        for {

            select {

            case request := <-runCh:

                go func() {

                    w.Run(&request)

                }()

            case <-shutdownSignal:

                w.Shutdown()

                return

            }

        }

    }(runCh, shutdownCh)

这部分我会有一些问题吗:


case request := <-runCh:

    go func() {

        w.Run(&request)

    }()

?


如果是,那为什么?


换句话说 -常见错误的循环迭代器变量部分使用 goroutines 是否也适用于我的案例,为什么它在这里适用/不适用?


烙印99
浏览 90回答 1
1回答

蝴蝶刀刀

不(不适用于此处),每次循环迭代都有新变量(内存地址):&nbsp;case request := <-runCh:因为这:=会创建与前一个不同的新变量,所以证明:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; runCh := make(chan int, 2)&nbsp; &nbsp; runCh <- 1&nbsp; &nbsp; runCh <- 2&nbsp; &nbsp; for i := 1; i <= 2; i++ {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case request := <-runCh:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(request, &request)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(200 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(request, &request)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; time.Sleep(500 * time.Millisecond)}输出(request每次循环迭代中的地址不同):1 0xc0000b80002 0xc0000b80081 0xc0000b80002 0xc0000b8008请参阅:0xc0000b8000 != 0xc0000b8008
随时随地看视频慕课网APP

相关分类

Go
我要回答