简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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