写一个生产者对象

2020-11-20 14:53:04 浏览数 (1)

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

代码语言:javascript复制
package main

import (
    "fmt"
    "time"
)

func main() {
    producer := NewProducer(MyWork, 10)
    for{
        result := <-producer.Ch
        fmt.Printf("% vn", 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
}

0 人点赞