正确使用缓冲通道的方法

时间:2015-01-26 14:16:58

标签: concurrency go

我有以下代码,使用goroutines和缓冲通道。我想知道,如果我以正确的方式使用频道。

package main

import (
    "errors"
    "fmt"
    "math/rand"
    "runtime"
    "time"
)

func random(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max-min) + min
}

func err1(rand int) <-chan error {
    output := make(chan error, 1)
    go func(n int) {
        if n == 1 {
            output <- errors.New("Error 1")
        }
        fmt.Println("Leave 1")
        close(output)
    }(rand)

    return output
}

func err2(rand int) <-chan error {
    output := make(chan error, 1)
    go func(n int) {
        if n == 2 {
            output <- errors.New("Error 2")
        }
        fmt.Println("Leave 2")
        close(output)
    }(rand)
    return output
}

func err3(rand int) <-chan error {
    output := make(chan error, 1)
    go func(n int) {
        if n == 3 {
            output <- errors.New("Error 3")
        }
        fmt.Println("Leave 3")
        close(output)
    }(rand)
    return output
}

func err4(rand int) <-chan error {
    output := make(chan error, 1)
    go func(n int) {
        if n == 3 {
            output <- errors.New("Error 4")
        }
        fmt.Println("Leave 4")
        close(output)
    }(rand)
    return output
}

func err5(rand int) <-chan error {
    output := make(chan error, 1)
    go func(n int) {
        if n == 4 {
            output <- errors.New("Error 5")
        }
        fmt.Println("Leave 5")
        close(output)
    }(rand)
    return output
}

func process(chs ...<-chan error) error {
    var err error

    for _, ch := range chs {
        err = <-ch
        if err != nil {
            //fmt.Println("Leave channel loop")
            break
        }
        //fmt.Println("Channel loop")
    }
    return err
}

func main() {

    runtime.GOMAXPROCS(runtime.NumCPU())

    n := random(1, 8)
    //n := 3
    fmt.Println(n)

    err := process(err1(n), err2(n), err3(n), err4(n), err5(n))
    fmt.Println(err)

    time.Sleep(time.Second * 3)

}

0 个答案:

没有答案