在select中的同一通道上读写

时间:2019-02-16 15:03:14

标签: go channel

是否可以使用一个通道在两个例程之间交换数据?

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)

1 个答案:

答案 0 :(得分:0)

works,但通常是个坏主意(tm)

您将来的软件维护者会为此而恨您

请注意,如果这些循环不完全相同,则当主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)
    }
}

输出:

 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.