两个 goroutine:go1,go2
go1 从 socket 读,读到的数据写到 ch1
go2 从 ch2 读,读到的数据写到 socket
以此来实现全双工通信
问题:ch1 关闭之后,go1 不知道,一写就崩了,怎么避免?
两个 goroutine:go1,go2
go1 从 socket 读,读到的数据写到 ch1
go2 从 ch2 读,读到的数据写到 socket
以此来实现全双工通信
问题:ch1 关闭之后,go1 不知道,一写就崩了,怎么避免?
|
shakeyoApr 27, 2021
1
创建一个用于通知的 chan
for 循环里监听这个 chan 是否有消息 在关闭的时候写入 在读取的时候监听 有信号退出当前 channel 就行 |
|
2
溴 ( xiù ) (英語:Bromine )是一種化學元素,其化學符號为 Br,原子序數为 35 —— 摘自维基百科
|
|
hwdefApr 27, 2021
3
从 ch 读的时候,可以检查是否已关闭了。
|
|
braderApr 27, 2021
4
这确实是个问题,需要今晚好好研究下
|
|
5
chan 仅由写的一方关闭
|
|
bruce00Apr 27, 2021
6
[How to Gracefully Close Channels]( https://go101.org/article/channel-closing.html)
```go func SafeSend(ch chan T, value T) (closed bool) { defer func() { if recover() != nil { closed = true } }() ch <- value // panic if ch is closed return false // <=> closed = false; return } ``` |
|
7
ch1 由 go1 关闭,也就是永远由写的一方关闭 channel
|
|
8
糗 qiǔ,溴 xiù
|
|
9
秀大了
|
|
linvonApr 27, 2021
10
go1 来关闭啊,怎么可能由消费者去关闭通道
go2 用 for range 去读,也能感知到关闭 |
|
11
你打标题的时候,又糗大了了一次。
|
|
LatinApr 27, 2021
12
我怀疑你是套娃 给自己问问题
|
|
name1991Apr 27, 2021
13
女同事很会发现问题
|
|
PresbyterApr 27, 2021
14
可以考虑用 context Cancel 控制一下
go1(ctx){ ... select{ case <-ctx.Done(): return ...... } ..... } |
|
SmartKeyerrorApr 27, 2021
15
The close built-in function closes a channel, which must be either bidirectional or send-only. It should be executed only by the sender, never the receiver, and has the effect of shutting down the channel after the last sent value is received.
https://pkg.go.dev/builtin#close |
|
yogogoApr 27, 2021
16
娶回家
|
|
freemoonApr 27, 2021
17
5 楼就是答案
|
|
zhaohuaApr 27, 2021
18
如果把问题简化为: 从关闭的 ch 中读取数据,如何才能不崩溃,答案是:做不到.
|
|
19
你又可以发一贴 在 V2EX 发帖 认错字了 糗大了
|
|
VegetableApr 28, 2021
20
没人提但是我很好奇,panic 了就 recover 一下不也算方案吗
|
|
yefuchaoApr 28, 2021
21
https://tour.golang.org/concurrency/4
A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression |
|
rekulasApr 30, 2021
22
用指针应该有办法判断,但并不是好办法,最好还是听楼上的意见自己处理关闭
|
|
iceteacoverMay 14, 2021
23
我是来抖机灵的:
不要把问技术问题女性当成女性。 不抖机灵的: 技术面前人人平等,请先尊重你同事的专业能力,再尊重性别。 |
|
Lihanx9Jun 8, 2021
24
如果是针对这个场景,不要求必须使用 channel 的话。goroutine 里用 io.Copy 读写,根据返回值或者异常判断结束退出 goroutine,另外 io.Copy 用在 net.Conn 上的时候,底层会调用 sendfile,零拷贝效率可能还会高一点。这是我最近遇到这个问题用的方法,不知道对不对啊...
|