SHARE
TWEET

Untitled

a guest Feb 23rd, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "time"
  6. )
  7.  
  8. var (
  9.     arr1 = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  10.     arr2 = []int{11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
  11. )
  12.  
  13. func main() {
  14.     withGO()
  15.  
  16. }
  17.  
  18. func withOutGo() {
  19.     defer timer()()
  20.     fmt.Println("sum arr1 : ", sum(arr1))
  21.     fmt.Println("sum arr2 : ", sum(arr2))
  22. }
  23.  
  24. func withGO() {
  25.     defer timer()()
  26.     chRes1 := make(chan int)
  27.     chRes2 := make(chan int)
  28.  
  29.     go func() {
  30.         chRes1 <- sum(arr1)
  31.     }()
  32.  
  33.     go func() {
  34.         chRes2 <- sum(arr2)
  35.     }()
  36.  
  37.     fmt.Println("sum arr1 : ", <-chRes1)
  38.     fmt.Println("sum arr2 : ", <-chRes2)
  39. }
  40.  
  41. func timer() func() {
  42.     t := time.Now()
  43.     return func() {
  44.         diff := time.Now().Sub(t)
  45.         fmt.Println(diff)
  46.     }
  47.  
  48. }
  49.  
  50. func sum(a []int) int {
  51.     s := 0
  52.     for _, x := range a {
  53.         s += x
  54.         time.Sleep(time.Millisecond * 100)
  55.     }
  56.     return s
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top