Go语言编程入门超级指南

2020-01-28 12:01:04王冬梅


package main

import (
    "fmt"
    "time"
)

/**
 * Output:
 * received message: hello
 * received message: world
 *
 * received from channel-1: Hello
 * received from channel-2: World
 *
 * received message: hello
 * Time out!
 *
 * Nothing received!
 * received message: hello
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * Nothing received!
 * received message: world
 * Nothing received!
 * Nothing received!
 * Nothing received!
 */
func main() {
    listenOnChannel()
    selectTwoChannels()

    blockChannelWithTimeout()
    unblockChannel()
}

func listenOnChannel() {
    // Specify channel type and buffer size
    channel := make(chan string, 5)

    go func() {
        channel <- "hello"
        channel <- "world"
    }()

    for i := 0; i < 2; i++ {
        msg := <- channel
        fmt.Println("received message: " + msg)
    }
}

func selectTwoChannels() {
    c1 := make(chan string)
    c2 := make(chan string)

    go func() {
        time.Sleep(time.Second)
        c1 <- "Hello"
    }()
    go func() {
        time.Sleep(time.Second)
        c2 <- "World"
    }()

    for i := 0; i < 2; i++ {
        select {
            case msg1 := <- c1:
                fmt.Println("received from channel-1: " + msg1)
            case msg2 := <- c2:
                fmt.Println("received from channel-2: " + msg2)
        }
    }
}

func blockChannelWithTimeout() {
    channel := make(chan string, 5)