我为什么关注这个问题?
原因很简单,我面试被问到了,面试并没有回答的很好^_~
有没有一个star比较多的例子?
写的很好的例子还是很多的,比如ant
// Pool accepts the tasks from client, it limits the total of goroutines to a given number by recycling goroutines.
type Pool struct {
// capacity of the pool, a negative value means that the capacity of pool is limitless, an infinite pool is used to
// avoid potential issue of endless blocking caused by nested usage of a pool: submitting a task to pool
// which submits a new task to the same pool.
capacity int32
// running is the number of the currently running goroutines.
running int32
// lock for protecting the worker queue.
lock sync.Locker
// workers is a slice that store the available workers.
workers workerQueue
// state is used to notice the pool to closed itself.
state int32
// cond for waiting to get an idle worker.
cond *sync.Cond
// workerCache speeds up the obtainment of a usable worker in function:retrieveWorker.
workerCache sync.Pool
// waiting is the number of goroutines already been blocked on pool.Submit(), protected by pool.lock
waiting int32
purgeDone int32
stopPurge context.CancelFunc
ticktockDone int32
stopTicktock context.CancelFunc
now atomic.Value
options *Options
}
应该怎么记住呢?
只有理解它他能永不忘记
- 首先需要一个size吧,要不你搞多大的并发数呢
- 得有个锁来保证资源安全吧,作为一个普通程序员,写的代码这个得算基本的保证了吧
- 得有个超时吧,要不业务写的不好都挂住了怎么办呢?
- 得有个队列吧,要不任务多了你放哪里呢?
4.1 为什么使用队列呢,使用栈可不可以呢
答案是:没有什么不可以,只是这种场景不适合使用栈
如果你能想到这些大概,协程池的架子是不是就差不多了,其他的记不住也能马马虎虎过吧
下面要说一下为什么选择队列,而不是栈呢?
堆和栈都是一种暂存数据的方式
不选择栈的最根本原因是因为栈的特性是先进后出,按照最简单的想法,我先提交的作业,竟然后调度!队列就比较好了,谁先来我先让谁先运行
其实栈的使用场景跟队列相比非常单一,我知道使用栈的场景只有编译器括号配对和字符串翻转的时候使用到,其他所有生产者和消费者的模型都是使用的队列(队列也有很多变种,比如优先级队列,延迟队列,双端队列)