zoukankan      html  css  js  c++  java
  • 分析一个简单的goroutine资源池

    分析一个简单的goroutine资源池 tunny

    从资源池中获取goroutine并进行处理的逻辑如下:

    tunny将goroutine处理单元封装为workWrapper,由此可以对goroutine的数目进行限制。

    workerWrapper.run()作为一个goroutine,内部负责具体事务的处理。其会将一个workRequest(可以看作是请求处理单元)放入reqChan,并阻塞等待使用方的调用。workRequest主要包含两个channel,其中jobChan用于传入调用方的输入,retChan用于给调用方返回执行结果。

    调用方会从pool的reqChan中获取一个workRequest请求处理单元,并在workRequest.jobChan中传参,这样workerWrapper.run()中就会继续进行work.process处理。处理结束之后将结果通过workRequest.retChan返回给调用方,然后继续通过reqChan <- workRequest阻塞等待下一个调用方的处理。

    其中workerWrapper.run()中的work是一个需要用户实现的接口,接口内容如下,最重要的接口是Process(interface{}) interface{}

    type Worker interface {
    	// Process will synchronously perform a job and return the result.
    	Process(interface{}) interface{}
    
    	// BlockUntilReady is called before each job is processed and must block the
    	// calling goroutine until the Worker is ready to process the next job.
    	BlockUntilReady()
    
    	// Interrupt is called when a job is cancelled. The worker is responsible
    	// for unblocking the Process implementation.
    	Interrupt()
    
    	// Terminate is called when a Worker is removed from the processing pool
    	// and is responsible for cleaning up any held resources.
    	Terminate()
    }
    

    结论

    tunny中的封装和处理函数并不适合所有的场景,但可以借鉴其核心思想来构造特定场景下的goroutine资源池。

  • 相关阅读:
    UVALive 7509 Dome and Steles
    HDU 5884 Sort
    Gym 101194H Great Cells
    HDU 5451 Best Solver
    HDU 5883 The Best Path
    HDU 5875 Function
    卡特兰数
    UVa 11729 Commando War 突击战
    UVa 11292 The Dragon of Loowater 勇者斗恶龙
    Spark Scala Flink版本对应关系
  • 原文地址:https://www.cnblogs.com/charlieroro/p/15735779.html
Copyright © 2011-2022 走看看