Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "errors"
- "log"
- "runtime"
- "time"
- )
- type Something struct {
- Id int64
- Data []byte
- }
- type getSomethingResult struct {
- Something *Something
- Error error
- }
- func GetSomething(id int64) (*Something, error) {
- result := make(chan getSomethingResult, 1)
- go func() {
- result <- doGetSomething(id)
- }()
- select {
- case <-time.After(5 * time.Second):
- return nil, errors.New("timed out")
- case result := <-result:
- return result.Something, result.Error
- }
- }
- func doGetSomething(id int64) getSomethingResult {
- time.Sleep(50 * time.Second)
- return getSomethingResult{
- Something: &Something{
- Id: 0,
- Data: nil,
- },
- Error: nil,
- }
- }
- func main() {
- for i := 0; i < 50; i++ {
- go GetSomething(1)
- }
- for {
- select {
- case <-time.After(1 * time.Second):
- log.Println(runtime.NumGoroutine()) // 51 goroutines are running in 5 seconds which is not good
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement