import (
"sync"
"unsafe"
+ "runtime"
"sync/atomic"
"container/list"
idpool "github.com/qydysky/part/idpool"
func (t *BlockFunc) UnBlock() {
t.Unlock()
+}
+
+type BlockFuncN struct{//新的等待旧的 个数
+ n int64
+ Max int64
+}
+
+func (t *BlockFuncN) Block() {
+ for {
+ now := atomic.LoadInt64(&t.n)
+ if now < t.Max && now >= 0 {break}
+ runtime.Gosched()
+ }
+ atomic.AddInt64(&t.n, 1)
+}
+
+func (t *BlockFuncN) UnBlock() {
+ for {
+ now := atomic.LoadInt64(&t.n)
+ if now > 0 {break}
+ runtime.Gosched()
+ }
+ atomic.AddInt64(&t.n, -1)
+}
+
+func (t *BlockFuncN) None() {
+ for !atomic.CompareAndSwapInt64(&t.n, 0, -1) {
+ runtime.Gosched()
+ }
+}
+
+func (t *BlockFuncN) UnNone() {
+ for !atomic.CompareAndSwapInt64(&t.n, -1, 0) {
+ runtime.Gosched()
+ }
}
\ No newline at end of file
go a(1)
go a(2)
time.Sleep(5*time.Second)
+}
+
+func Test_BlockFuncN(t *testing.T) {
+ var b = BlockFuncN{
+ Max:2,
+ }
+ var a = func(i int){
+ b.Block()
+ defer b.UnBlock()
+ t.Log(i,`.`)
+ time.Sleep(time.Second)
+ t.Log(i,`.`)
+ }
+ t.Log(`show two . at one time`)
+ go a(1)
+ go a(2)
+ go a(3)
+ time.Sleep(5*time.Second)
}
\ No newline at end of file