Using channel to communicate Goroutine – Goroutine

In big program and you need to use big number goroutines to process something. I make sure you will face to face with issue, how to send data from goroutine to other gorountine

Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine.

ch <- v    // Send v to channel ch.
v := <-ch  // Receive from ch, and
           // assign value to v.

(The data flows in the direction of the arrow.)

I have an example. I want sum elements of integer array. But I don’t want to loop all array to sum, it is slow. I will use goroutine, get sum of 1st half and 2nd half of array, and result = 1st sum + 2nd sum. It’s double fastness

Like maps and slices, channels must be created before use: c := make(chan int)

By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.

1st goroutine, I make sum 7,2,8 and send 1st sum to channel

2nd goroutine, I make sum -9, 4, 0 and send 2nd sum to channel

I no need to know 1st or 2nd complete first. I only use x, y to receive results of them. When I have enough results, final result is x + y

Because I use 2 goroutine for sum on array. Maybe program should be double fast

package main

import "fmt"

func sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	c <- sum // send sum to c

func main() {
	s := []int{7, 2, 8, -9, 4, 0}

	c := make(chan int)
	go sum(s[:len(s)/2], c)
	go sum(s[len(s)/2:], c)
	x, y := <-c, <-c // receive from c

	fmt.Println(x, y, x+y)

View on github