美文网首页程序员
写一个生产者对象

写一个生产者对象

作者: yellowone | 来源:发表于2020-07-08 08:06 被阅读0次

    在go语言里面,进程之间的通讯鼓励的是利用chan去通信,常见的进程通讯就是消费者和生产者,通过函数接口和异步生产者调用,可以实现一个生产者对象。

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        producer := NewProducer(MyWork, 10)
        for{
            result := <-producer.Ch
            fmt.Printf("%+v\n", result)
        }
    }
    
    func MyWork() interface{} {
        time.Sleep(1 * time.Second)
        return "任务结果"
    }
    
    type Producer struct {
        Ch chan interface{}
    }
    
    type Work func() interface{}
    
    func NewProducer(work Work, cacheLen int) *Producer {
        producer := &Producer{Ch: make(chan interface{}, cacheLen)}
        go func() {
            for {
                result := work()
                producer.Ch <- result
            }
        }()
        return producer
    }
    
    

    相关文章

      网友评论

        本文标题:写一个生产者对象

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