简体   繁体   English

在select中的同一通道上读写

[英]Read and write on the same channel in select

Is it OK to exchange data between two routines using one channel this way? 这样可以使用一个通道在两个例程之间交换数据吗?

c := make(chan int)

go func() {
    var i int
    select {
    case c<- 1:
        i = <-c
    case i = <-c:
        c<- 1
    }
    fmt.Println(" A - Written 1 red ", i)
}()

var i int
select {
case c<- 2:
    i = <-c
case i = <-c:
    c<- 2
}
fmt.Println(" B - Written 2 red ", i)

It works , but is generally a bad idea(tm) 可以工作 ,但通常是个坏主意(tm)

your future software maintainers will hate you for it 您未来的软件维护者会为此而恨您

Note, if those loops are not exactly the same, then the app will crash with when the main goroutine blocks due to noone else writing or reading 请注意,如果这些循环不完全相同,则当主goroutine阻塞时,由于没有其他人在读或写,因此应用程序将崩溃

package main

import (
    "fmt"
)

func main() {
    c := make(chan int)

    go func() {
        for x := 0; x < 5; x++ {
            var i int
            select {
            case c <- 1:
                i = <-c
            case i = <-c:
                c <- 1
            }
            fmt.Println(" A - Written 1 red ", i)
        }
    }()
    for x := 0; x < 5; x++ {
        var i int
        select {
        case c <- 2:
            i = <-c
        case i = <-c:
            c <- 2
        }
        fmt.Println(" B - Written 2 red ", i)
    }
}

Output: 输出:

 B - Written 2 red  1
 A - Written 1 red  2
 B - Written 2 red  1
 A - Written 1 red  2
 B - Written 2 red  1
 A - Written 1 red  2
 B - Written 2 red  1
 A - Written 1 red  2
 B - Written 2 red  1

Program exited.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM