channel 生产者消费者

2019-06-19  本文已影响0人  jaydenZou1228
package main

import (
    "fmt"
    "time"
)

func producer(c chan int) {
    for i := 0; i < 3; i++ {
        fmt.Printf("Alice puts product, ID is : %d \n", i)
        c <- i
        time.Sleep(time.Second)
    }
    defer close(c)
}
func consumer(c chan int) {
    hasMore := true
    var p int
    for hasMore {
        if p, hasMore = <-c; hasMore {
            fmt.Printf("Bob gets product, ID is : %d \n", p)
        }
    }
}

func main() {
    c := make(chan int)
    go producer(c)
    consumer(c)
}
上一篇 下一篇

猜你喜欢

热点阅读