]> 127.0.0.1 Git - part/.git/commitdiff
add TK func for limit v0.5.5
authorqydysky <qydysky@foxmail.com>
Mon, 12 Apr 2021 07:39:27 +0000 (15:39 +0800)
committerqydysky <qydysky@foxmail.com>
Mon, 12 Apr 2021 07:39:27 +0000 (15:39 +0800)
limit/Limit.go
limit/Limit_test.go

index 6489be754b16162afd4c3dc14fb5ab17d8e7bc09..410a2c898a60c5da671b27ce75e3b67039d02f9b 100644 (file)
@@ -8,7 +8,7 @@ type Limit struct {
        maxNum_in_period int
        ms_in_period int
        ms_to_timeout int
-       channl chan struct{}
+       bucket chan struct{}
 }
 
 // create a Limit Object
@@ -18,26 +18,34 @@ func New(maxNum_in_period,ms_in_period,ms_to_timeout int) (*Limit) {
                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
index be2730f7f88f490f85059bc534112b466bf16e72..744144926b8479aaf4634f818849bee30c2e049b 100644 (file)
@@ -51,4 +51,13 @@ func Test_4(t *testing.T){
                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