select.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. var start time.Time
  7. func init() {
  8. fmt.Println("init...")
  9. start = time.Now()
  10. }
  11. func service1(c chan string) {
  12. // time.Sleep(3 * time.Second)
  13. fmt.Println("service1() started", time.Since(start))
  14. c <- "Hello from service 1"
  15. }
  16. func service2(c chan string) {
  17. // time.Sleep(5 * time.Second)
  18. fmt.Println("service2() started", time.Since(start))
  19. c <- "Hello from service 2"
  20. }
  21. func main() {
  22. selectTest()
  23. /*
  24. fmt.Println("main() started", time.Since(start))
  25. chan1 := make(chan string)
  26. chan2 := make(chan string)
  27. go service1(chan1)
  28. go service2(chan2)
  29. select {
  30. case res := <-chan1:
  31. fmt.Println("Response from service 1", res, time.Since(start))
  32. case res := <-chan2:
  33. fmt.Println("Response from service 2", res, time.Since(start))
  34. }
  35. fmt.Println("main() stopped", time.Since(start))
  36. */
  37. }
  38. func selectTest() {
  39. fmt.Println("main() started", time.Since(start))
  40. chan1 := make(chan string)
  41. chan2 := make(chan string)
  42. go service1(chan1)
  43. go service2(chan2)
  44. // С этой функций в select выполнится один из кейсов
  45. // Без задержки будет выполнен default
  46. // time.Sleep(1 * time.Second)
  47. select {
  48. case res := <-chan1:
  49. fmt.Println("Response from service 1", res, time.Since(start))
  50. case res := <-chan2:
  51. fmt.Println("Response from service 2", res, time.Since(start))
  52. // default:
  53. // fmt.Println("No responce received", time.Since(start))
  54. }
  55. fmt.Println("main() stopped", time.Since(start))
  56. }