设计一个协程池需要注意哪些地方?

我为什么关注这个问题?

原因很简单,我面试被问到了,面试并没有回答的很好^_~

有没有一个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
}

应该怎么记住呢?

只有理解它他能永不忘记

  1. 首先需要一个size吧,要不你搞多大的并发数呢
  2. 得有个锁来保证资源安全吧,作为一个普通程序员,写的代码这个得算基本的保证了吧
  3. 得有个超时吧,要不业务写的不好都挂住了怎么办呢?
  4. 得有个队列吧,要不任务多了你放哪里呢?
    4.1 为什么使用队列呢,使用栈可不可以呢
    答案是:没有什么不可以,只是这种场景不适合使用栈

如果你能想到这些大概,协程池的架子是不是就差不多了,其他的记不住也能马马虎虎过吧

下面要说一下为什么选择队列,而不是栈呢?

堆和栈都是一种暂存数据的方式
不选择栈的最根本原因是因为栈的特性是先进后出,按照最简单的想法,我先提交的作业,竟然后调度!队列就比较好了,谁先来我先让谁先运行


其实栈的使用场景跟队列相比非常单一,我知道使用栈的场景只有编译器括号配对和字符串翻转的时候使用到,其他所有生产者和消费者的模型都是使用的队列(队列也有很多变种,比如优先级队列,延迟队列,双端队列)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值