ANi*_*sus 31 concurrency select channel go
我希望在两个通道上进行常规监听,当两个通道都耗尽时阻塞.但是,如果两个通道都包含数据,我希望在处理另一个通道之前将其耗尽.
在下面的工作示例中,我希望out在exit处理之前将所有内容都耗尽.我使用select没有任何优先顺序的-statement.我如何解决问题,在退出之前处理所有10个输出值?
package main
import "fmt"
func sender(out chan int, exit chan bool){
for i := 1; i <= 10; i++ {
out <- i
}
exit <- true
}
func main(){
out := make(chan int, 10)
exit := make(chan bool)
go sender(out, exit)
L:
for {
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
case <-exit:
fmt.Println("Exiting")
break L
}
}
fmt.Println("Did we get all 10? Most likely not")
}
Run Code Online (Sandbox Code Playgroud)
jor*_*lli 34
该语言本身支持此功能,无需解决方法.这很简单:退出通道应该只对生产者可见.退出时,制作人关闭频道.只有当渠道为空并关闭时,消费者才会退出.这可以通过以下方式从频道中读取:
v, ok := <-c
Run Code Online (Sandbox Code Playgroud)
这将设置ok为一个布尔值,指示该值v是否实际从通道(ok == true)中读取,或者是否v设置为通道处理类型的零值,c因为c它已关闭且为空(ok == false).当通道关闭且非空时,v将是有效值并且ok将是true.当通道关闭并且为空时,v将是通道处理的类型的零值c,并且ok将false表示v没用.
这是一个例子来说明:
package main
import (
"fmt"
"math/rand"
"time"
)
var (
produced = 0
processed = 0
)
func produceEndlessly(out chan int, quit chan bool) {
defer close(out)
for {
select {
case <-quit:
fmt.Println("RECV QUIT")
return
default:
out <- rand.Int()
time.Sleep(time.Duration(rand.Int63n(5e6)))
produced++
}
}
}
func quitRandomly(quit chan bool) {
d := time.Duration(rand.Int63n(5e9))
fmt.Println("SLEEP", d)
time.Sleep(d)
fmt.Println("SEND QUIT")
quit <- true
}
func main() {
vals, quit := make(chan int, 10), make(chan bool)
go produceEndlessly(vals, quit)
go quitRandomly(quit)
for {
x, ok := <-vals
if !ok {
break
}
fmt.Println(x)
processed++
time.Sleep(time.Duration(rand.Int63n(5e8)))
}
fmt.Println("Produced:", produced)
fmt.Println("Processed:", processed)
}
Run Code Online (Sandbox Code Playgroud)
这一点记录在go规范的"接收运算符"部分:http://golang.org/ref/spec#Receive_operator
Son*_*nia 24
package main
import "fmt"
func sender(out chan int, exit chan bool) {
for i := 1; i <= 10; i++ {
out <- i
}
exit <- true
}
func main() {
out := make(chan int, 10)
exit := make(chan bool)
go sender(out, exit)
for {
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
continue
default:
}
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
continue
case <-exit:
fmt.Println("Exiting")
}
break
}
fmt.Println("Did we get all 10? I think so!")
}
Run Code Online (Sandbox Code Playgroud)
第一个选择的默认情况使其无阻塞.选择将在不查看退出通道的情况下排出输出通道,否则将不会等待.如果out通道为空,它会立即下降到第二个选择.第二个选择是阻止.它将等待任一通道上的数据.如果出口,它会处理它并允许循环退出.如果数据到来,它会回到循环的顶部并返回到排水模式.
是的,至少可以说这不太好,但是 100% 做到了所需要的,没有陷阱,也没有隐藏的限制。
这是一个简短的代码示例,解释如下。
package main
import(
"fmt"
"time"
)
func sender(out chan int, exit chan bool) {
for i := 1; i <= 10; i++ {
out <- i
}
time.Sleep(2000 * time.Millisecond)
out <- 11
exit <- true
}
func main(){
out := make(chan int, 20)
exit := make(chan bool)
go sender(out, exit)
time.Sleep(500 * time.Millisecond)
L:
for {
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
default:
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
case <-exit:
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
default:
fmt.Println("Exiting")
break L
}
}
}
}
fmt.Println("Did we get all 10? Yes.")
fmt.Println("Did we get 11? DEFINITELY YES")
}
Run Code Online (Sandbox Code Playgroud)
main()从上面注释:func main(){
out := make(chan int, 20)
exit := make(chan bool)
go sender(out, exit)
time.Sleep(500 * time.Millisecond)
L:
for {
select {
// here we go when entering next loop iteration
// and check if the out has something to be read from
// this select is used to handle buffered data in a loop
case i := <-out:
fmt.Printf("Value: %d\n", i)
default:
// else we fallback in here
select {
// this select is used to block when there's no data in either chan
case i := <-out:
// if out has something to read, we unblock, and then go the loop round again
fmt.Printf("Value: %d\n", i)
case <-exit:
select {
// this select is used to explicitly propritize one chan over the another,
// in case we woke up (unblocked up) on the low-priority case
// NOTE:
// this will prioritize high-pri one even if it came _second_, in quick
// succession to the first one
case i := <-out:
fmt.Printf("Value: %d\n", i)
default:
fmt.Println("Exiting")
break L
}
}
}
}
fmt.Println("Did we get all 10? Yes.")
fmt.Println("Did we get 11? DEFINITELY YES")
}
Run Code Online (Sandbox Code Playgroud)
注意:在玩弄优先级的技巧之前,请确保您正在解决正确的问题。
很可能,它可以用不同的方式解决。
尽管如此,在 Go 中优先选择 select 仍然是一件很棒的事情。只是个梦..
注意:这是一个非常相似的答案/sf/answers/3209804181/在此线程上,但只有两个 select- 嵌套,而不是像我那样三个。有什么不同?我的方法更有效,并且我们明确期望在每次循环迭代中处理随机选择。
但是,如果高优先级通道没有缓冲,和/或您不期望其上有大量数据,只有零星的单个事件,那么更简单的两阶段习惯用法(如该答案中所示)就足够了:
L:
for {
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
case <-exit:
select {
case i := <-out:
fmt.Printf("Value: %d\n", i)
default:
fmt.Println("Exiting")
break L
}
}
}
Run Code Online (Sandbox Code Playgroud)
它基本上是 2 和 3 个阶段,第 1 阶段被删除。
再说一次:在大约 90% 的情况下,您认为确实需要优先考虑 chan 切换情况,但实际上不需要。
这是一个可以封装在宏中的单行代码:
for {
select { case a1 := <-ch_p1: p1_action(a1); default: select { case a1 := <-ch_p1: p1_action(a1); case a2 := <-ch_p2: select { case a1 := <-ch_p1: p1_action(a1); default: p2_action(a2); }}}
}
Run Code Online (Sandbox Code Playgroud)
那么你有两个选择。第一个 - 使用中间 goroutine 构建一棵树,以便每个分叉完全是二元的(上面的习惯用法)。
第二种选择是使优先级分叉增加一倍以上。
以下是三个优先级的示例:
for {
select {
case a1 := <-ch_p1:
p1_action(a1)
default:
select {
case a2 := <-ch_p2:
p2_action(a2)
default:
select { // block here, on this select
case a1 := <-ch_p1:
p1_action(a1)
case a2 := <-ch_p2:
select {
case a1 := <-ch_p1:
p1_action(a1)
default:
p2_action(a2)
}
case a3 := <-ch_p3:
select {
case a1 := <-ch_p1:
p1_action(a1)
case a2 := <-ch_p2:
p1_action(a2)
default:
p2_action(a3)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,整个结构在概念上分为三个部分,作为原始(二进制)部分。
PS,反问:为什么 Golang 没有将其内置到语言中???问题是修辞一。
另一种方法:
package main
import "fmt"
func sender(c chan int) chan int {
go func() {
for i := 1; i <= 15; i++ {
c <- i
}
close(c)
}()
return c
}
func main() {
for i := range sender(make(chan int, 10)) {
fmt.Printf("Value: %d\n", i)
}
fmt.Println("Did we get all 15? Surely yes")
}
Run Code Online (Sandbox Code Playgroud)
$ go run main.go
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Value: 6
Value: 7
Value: 8
Value: 9
Value: 10
Value: 11
Value: 12
Value: 13
Value: 14
Value: 15
Did we get all 15? Surely yes
$
Run Code Online (Sandbox Code Playgroud)