关于golang:聊聊tunny的workerWrapper

46次阅读

共计 1689 个字符,预计需要花费 5 分钟才能阅读完成。

本文次要钻研一下 tunny 的 workerWrapper

workerWrapper

type workerWrapper struct {
    worker        Worker
    interruptChan chan struct{}

    // reqChan is NOT owned by this type, it is used to send requests for work.
    reqChan chan<- workRequest

    // closeChan can be closed in order to cleanly shutdown this worker.
    closeChan chan struct{}

    // closedChan is closed by the run() goroutine when it exits.
    closedChan chan struct{}}

func newWorkerWrapper(
    reqChan chan<- workRequest,
    worker Worker,
) *workerWrapper {
    w := workerWrapper{
        worker:        worker,
        interruptChan: make(chan struct{}),
        reqChan:       reqChan,
        closeChan:     make(chan struct{}),
        closedChan:    make(chan struct{}),
    }

    go w.run()

    return &w
}

workerWrapper 包装了 worker,定义了 interruptChan、reqChan、closeChan、closedChan 属性

interrupt

func (w *workerWrapper) interrupt() {close(w.interruptChan)
    w.worker.Interrupt()}

interrupt 办法敞开 w.interruptChan,执行 w.worker.Interrupt()

run

func (w *workerWrapper) run() {jobChan, retChan := make(chan interface{}), make(chan interface{})
    defer func() {w.worker.Terminate()
        close(retChan)
        close(w.closedChan)
    }()

    for {
        // NOTE: Blocking here will prevent the worker from closing down.
        w.worker.BlockUntilReady()
        select {
        case w.reqChan <- workRequest{
            jobChan:       jobChan,
            retChan:       retChan,
            interruptFunc: w.interrupt,
        }:
            select {
            case payload := <-jobChan:
                result := w.worker.Process(payload)
                select {
                case retChan <- result:
                case <-w.interruptChan:
                    w.interruptChan = make(chan struct{})
                }
            case _, _ = <-w.interruptChan:
                w.interruptChan = make(chan struct{})
            }
        case <-w.closeChan:
            return
        }
    }
}

run 首先创立 jobChan、retChan,而后 for 循环执行 select 读取 reqChan,之后读取 jobChan 的 payload,进行解决,而后写入到 retChan

stop

func (w *workerWrapper) stop() {close(w.closeChan)
}

stop 办法敞开 w.closeChan

join

func (w *workerWrapper) join() {<-w.closedChan}

join 办法则期待 w.closedChan

小结

tunny 的 workerWrapper 包装了 worker,定义了 interruptChan、reqChan、closeChan、closedChan 属性,它提供了 interrupt、run、stop、join 办法。

doc

  • tunny

正文完
 0