Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. func total(ch chan int) {
  8. res := 0
  9. for iter := range ch {
  10. res += iter
  11. }
  12. ch <- res
  13. }
  14.  
  15. func main() {
  16. ch := make(chan int)
  17. go total(ch)
  18. ch <- 1
  19. ch <- 2
  20. ch <- 3
  21. fmt.Println("Total is ", <-ch)
  22. }
  23.  
  24. throw: all goroutines are asleep - deadlock!
  25.  
  26. package main
  27.  
  28. import (
  29. "fmt"
  30. )
  31.  
  32. func total(in chan int, out chan int) {
  33. res := 0
  34. for iter := range in {
  35. res += iter
  36. }
  37. out <- res // sends back the result
  38. }
  39.  
  40. func main() {
  41. ch := make(chan int)
  42. rch := make(chan int)
  43. go total(ch, rch)
  44. ch <- 1
  45. ch <- 2
  46. ch <- 3
  47. close (ch) // this will end the loop in the total function
  48. result := <- rch // waits for total to give the result
  49. fmt.Println("Total is ", result)
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement