go - 是否关闭 channel 阻塞直到接收者读取它

标签 go concurrency channel goroutine

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

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()
}

最佳答案

没有。使用sync.WaitGroup相反。

关于go - 是否关闭 channel 阻塞直到接收者读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52146709/

相关文章:

python-2.7 - 如何在 Python 中使用 OpenCV 合并 2 个灰度图像

c++ - SDL_Mixer 是否可以在自身上播放单个 block ?

go - 私有(private)仓库 - go 1.13 - `go mod ..` 失败 : ping "sum.golang.org/lookup" . 。正在验证包.. 410 消失了

java - 我可以从并发线程调用 XMPPConnection.sendPacket 吗?

java - 如何实现多个线程安全的读/写锁(ConcurrentHashmap)

wpf - 当mouseup事件触发动画时,WPF UI线程会暂时卡住

django - 简单的 django channel 应用程序未与 daphne 一起运行

xml 编码和解码 xsi :type

mysql - Golang Gorm : Same query constructed differently throwing different results

go - 将文件存储在可执行二进制文件中