首页 > 解决方案 > 是否关闭通道块直到接收器读取它

问题描述

我已经实现了一种通过关闭通道来关闭服务器的方法,因此其他 goroutines 读取关闭的通道然后退出。关闭后,我需要对服务器数据进行一些清理,如果close()阻塞直到所有其他 goroutine 读取关闭的通道,我可以无锁访问数据。所以问题是:关闭通道会阻塞直到接收器从中读取吗?下面是示例代码:

package main

type server struct {
    chStop chan struct{}
    data map[int]interface{}
}

func newServer() *server {
    return &server {
        chStop: make(chan struct{})
    }
}

func (s *server) stop() {
    close(s.chStop)
    // do something with s.data
    ...
    // if other goroutines already read closed s.chStop and exited,
    // we can access s.data without lock
}

func (s *server) run2() {
    ...
    for {
        select{
        case <-s.chStop:
            return
        case <- other channel:
        // access s.data with lock
        }
    }
}

func (s *server) run() {
    ch := make(chan struct{})
    ...
    for {
        select{
        case <-s.chStop:
            return
        case <- ch:
            // access s.data with lock
        }
    }
}

func main() {
    s := newServer()
    go s.run()
    go s.run2()
    s.stop()
}

标签: goconcurrencychannelgoroutine

解决方案


不,请改用 a sync.WaitGroup


推荐阅读