Go语言中使用 buffered channel 实现线程安全的 pool
概述
我们已经知道Go语言提供了sync.Pool,但是做的不怎么好,所以有必要自己来实现一个pool。
给我看代码:
typePoolstruct{ poolchan*Client }
//创建一个新的pool funcNewPool(maxint)*Pool{ return&Pool{ pool:make(chan*Client,max), } }
//从pool里借一个Client func(p*Pool)Borrow()*Client{ varcl*Client select{ casecl=<-p.pool: default: cl=newClient() } returncl }
//还回去 func(p*Pool)Return(cl*Client){ select{ casep.pool<-cl: default: //letitgo,letitgo... } }