maxNum_in_period int
ms_in_period int
ms_to_timeout int
- channl chan struct{}
+ bucket chan struct{}
}
// create a Limit Object
maxNum_in_period:maxNum_in_period,
ms_in_period:ms_in_period,
ms_to_timeout:ms_to_timeout,
- channl:make(chan struct{},maxNum_in_period),
+ bucket:make(chan struct{},maxNum_in_period),
}
go func(object *Limit){
for object.maxNum_in_period > 0 {
for i:=1;i<=object.maxNum_in_period;i++{
- object.channl <- struct{}{}
+ object.bucket <- struct{}{}
}
time.Sleep(time.Duration(object.ms_in_period)*time.Millisecond)
}
}(&object)
+ //make sure the bucket is full
+ for object.TK() != maxNum_in_period {}
+
return &object
}
// the func will return true if the request(call TO()) is up to limit and return false if not
func (l *Limit) TO() bool {
select {
- case <-l.channl :;
+ case <-l.bucket :;
case <-time.After(time.Duration(l.ms_to_timeout)*time.Millisecond):return true;
}
return false
+}
+
+// return the token number of bucket
+func (l *Limit) TK() int {
+ return len(l.bucket)
}
\ No newline at end of file
time.Sleep(time.Millisecond)
}
t.Log(pass)
+}
+
+func Test_5(t *testing.T){
+ l := New(100,5000,0)
+ for i:=0;i<50;i+=1{
+ l.TO()
+ time.Sleep(time.Millisecond)
+ }
+ if l.TK() != 50 {t.Error(`5`,l.TK())}
}
\ No newline at end of file