Advertisement
Guest User

Untitled

a guest
Aug 29th, 2023
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.09 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "errors"
  5.     "log"
  6.     "runtime"
  7.     "time"
  8. )
  9.  
  10. type Something struct {
  11.     Id   int64
  12.     Data []byte
  13. }
  14.  
  15. type getSomethingResult struct {
  16.     Something *Something
  17.     Error     error
  18. }
  19.  
  20. func GetSomething(id int64) (*Something, error) {
  21.     result := make(chan getSomethingResult, 1)
  22.     go func() {
  23.         result <- doGetSomething(id)
  24.     }()
  25.     select {
  26.     case <-time.After(5 * time.Second):
  27.         return nil, errors.New("timed out")
  28.     case result := <-result:
  29.         return result.Something, result.Error
  30.     }
  31. }
  32.  
  33. func doGetSomething(id int64) getSomethingResult {
  34.     time.Sleep(50 * time.Second)
  35.     return getSomethingResult{
  36.         Something: &Something{
  37.             Id:   0,
  38.             Data: nil,
  39.         },
  40.         Error: nil,
  41.     }
  42. }
  43.  
  44. func main() {
  45.     for i := 0; i < 50; i++ {
  46.         go GetSomething(1)
  47.     }
  48.  
  49.     for {
  50.  
  51.         select {
  52.         case <-time.After(1 * time.Second):
  53.             log.Println(runtime.NumGoroutine()) // 51 goroutines are running in 5 seconds which is not good
  54.         }
  55.  
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement