• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

Recommended Posts

先贴原作者仓库地址:https://github.com/panjf2000/ants.

一般来说,线程池的存在是为了在高并发的情况下实现线程复用,从而减少内存开销,提高执行速度。

认为个人蚂蚁的设计有两点需要学习:池调度模型和自旋锁。

池模型

调度流程

检查当前工作者队列中是否有可用的工作者,如果有,取出并执行当前任务;

没有可用的Worker,所以判断当前运行的Worker是否已经超过了这个池的容量:{ Yes-然后判断工作池是否处于非阻塞模式:【Yes,3354,直接返回nil,no,3354,阻塞等待一个Worker放回池中】,no-打开一个新的Worker(goroutine)进行处理};

每个工作线程完成任务后,将其放回池的队列中等待。

自旋锁

定义:当一个线程试图获取一个锁的时候,如果这个锁已经被别人获取(占用)了,那么这个线程就无法获取这个锁,这个线程会等待一段时间间隔后再尝试获取。

为了在ants中实现自旋锁,使用了二进制指数规避算法,代码如下:

自旋锁uint32标牌

const maxBackoff=16

func (sl *spinLock) Lock() {

后退:=1

为了!原子的。compareandswapuint 32((* uint 32)(sl),0,1) {

//利用指数补偿算法,参见https://en.wikipedia.org/wiki/Exponential_backoff.

对于I :=0;我后退;我{

运行时。戈舍德()

}

if backoff maxBackoff {

后退=1

}

}

}

func (sl *spinLock) Unlock() {

原子的。StoreUint32((*uint32)(sl),0)

}

//NewSpinLock实例化一个自旋锁。

func NewSpinLock() sync。储物柜{

返回新的(自旋锁)

}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now