Go语言tunny的workerWrapper使用教程示例

2023-12-05 0 603
目录
  • workerWrapper
  • interrupt
  • run
  • stop
  • join
  • 小结

本文主要研究一下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

以上就是Go语言tunny的workerWrapper使用教程示例的详细内容,更多关于go tunny workerWrapper教程的资料请关注悠久资源网其它相关文章!

您可能感兴趣的文章:

  • golang的tunny的用法示例教程
  • go语言定义零值可用的类型学习教程
  • Go语言学习网络编程与Http教程示例
  • 从Context到go设计理念轻松上手教程
  • Go语言数据结构之双链表学习教程
  • Go错误和异常CGO fallthrough处理教程详解
  • goswagger生成接口文档使用教程

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Golang Go语言tunny的workerWrapper使用教程示例 https://www.u-9.cn/jiaoben/golang/102105.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务