ants源碼解析(GO)

用來管理goroutine的工具,執行一個task就調度一個worker來運行,而後對worker進行管理,一個worker也至關於一個goroutine.bash


ants用一個pool管理worker,負責worker的調度還有回收app

type Pool struct {	// capacity of the pool.	capacity int32	// running is the number of the currently running goroutines.	running int32	// expiryDuration set the expired time (second) of every worker.	expiryDuration time.Duration	// workers is a slice that store the available workers.	workers []*goWorker	// release is used to notice the pool to closed itself.	release int32	// lock for synchronous operation.	lock sync.Mutex	// cond for waiting to get a idle worker.	cond *sync.Cond	// once makes sure releasing this pool will just be done for one time.	once sync.Once	// workerCache speeds up the obtainment of the an usable worker in function:retrieveWorker.	workerCache sync.Pool	// panicHandler is used to handle panics from each worker goroutine.	// if nil, panics will be thrown out again from worker goroutines.	panicHandler func(interface{})	// Max number of goroutine blocking on pool.Submit.	// 0 (default value) means no such limit.	maxBlockingTasks int32	// goroutine already been blocked on pool.Submit	// protected by pool.lock	blockingNum int32	// When nonblocking is true, Pool.Submit will never be blocked.	// ErrPoolOverload will be returned when Pool.Submit cannot be done at once.	// When nonblocking is true, MaxBlockingTasks is inoperative.	nonblocking bool}type goWorker struct {	// pool who owns this worker.	pool *Pool	// task is a job should be done.	task chan func()	// recycleTime will be update when putting a worker back into queue.	recycleTime time.Time}複製代碼




從pool中獲取一個可用worker工具

pool -> retrieveWorker():
判斷p.workers是否有閒置的worker能夠取,有的話,從最後取出一個worker.
若p.workers沒有閒置的worker能夠取,則判斷運行中的worker是否達到上限, 若沒有,從p.workerCache取出一個woker,若p.workerCache沒有就新建一個worker.
若運行中的worker達到上限,且是不阻塞的pool則直接返回nil.
若運行中的worker達到上限,且是阻塞的pool,則再阻塞數量沒超過限定的數量時,p.blockingNum++並等待信號.
接收到信號的時候p.blockingNum—,判斷p.workers中是否有能夠運行的worker,有則返回worker,若沒有則從新阻塞.



釋放pool裏的workerui

pool -> Release():this

只執行一次
p.release置1
全部worker都傳nil task



調整pool中worker數量:spa

tune(size uint)code


除了pool,worker.但確認執行的task中的func都是同樣時,可用pool_func,worker_func.其中傳遞不是task了,而是task執行的參數.worker獲取到參數,就塞進默認的func來執行.cdn

相關文章
相關標籤/搜索