Created
December 22, 2017 01:19
-
-
Save arfan/76e065e811e59b0858f77f2301868a87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"sync" | |
"sync/atomic" | |
"time" | |
"github.com/korovkin/limiter" | |
) | |
func main() { | |
var total int64 | |
nTask := 100 | |
nRoutine := 10 | |
ch := make(chan int) | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go func() { | |
for i := 0; i < nTask; i++ { | |
ch <- i | |
} | |
wg.Done() | |
}() | |
limit := limiter.NewConcurrencyLimiter(nRoutine) | |
for i := 0; i < nTask; i++ { | |
limit.Execute(func() { | |
// do some work | |
x := <-ch | |
result := fungsiBodoh(x) | |
fmt.Println(result) | |
atomic.AddInt64(&total, int64(result)) | |
time.Sleep(time.Second * 2) | |
}) | |
} | |
limit.Wait() | |
fmt.Println(total) | |
} | |
func fungsiBodoh(x int) int { | |
time.Sleep(time.Duration(random(500, 4500)) * time.Millisecond) | |
return x * x | |
} | |
func random(min, max int) int { | |
rand.Seed(time.Now().Unix()) | |
return rand.Intn(max-min) + min | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment