美文网首页
channel 生产者消费者

channel 生产者消费者

作者: jaydenZou1228 | 来源:发表于2019-06-19 10:11 被阅读0次
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)
}

相关文章

网友评论

      本文标题:channel 生产者消费者

      本文链接:https://www.haomeiwen.com/subject/kakhqctx.html