1/17/2017 - 3:56 AM

Go - Channels and goroutine example

Go - Channels and goroutine example

import (

func sum(list []int, ch chan int) {
sum := 0
for _, v := range list {
sum += v

fmt.Println("==In sum func==", sum)

ch - sum // send sum to ch

func main() {
list1 := []int{2, 4, 6}
list2 := []int{1, 3, 7, 11}

ch1 := make(chan int, 5)

go sum(list1, ch1)
go sum(list2, ch1)

//fmt.Println("==In main func==", -ch1)
fmt.Println("==In main func==", -ch1)

//Go program ends when the main function ends.
//So goroutine doesn't get time to run and print its output.
//main() func need to wait for our goroutines to finish.
//For debugging, we can add sleep in main() func and give time to goroutines to finish.
//from channel, we cannot read more than what we sent.
//fmt.Println("==In sum func==", -ch)