I. Introduction

Message passing is a technique that is highly appreciated in programming. Compare to shared memory, some pro-golang developers prefer message passing.

In summary about message passing, we can understand that we produce messages consumed by the consumer, the message is produced and consumed once! When you put a message into a channel, the operation is blocked until it is read by the consumer.

Channel is like a pipeline that goroutines use to communicate with each other, it helps to solve the problem of sharing resource between goroutines

Channel in golang

II. Implementation

Now, let’s see the syntax of the channel in golang

package main

var (
	channel = make(chan string) // remember that each channel can only take care one type of data
)

func main() {
	channel <- "harry duong" // put data into channel
	name := <-channel        // receive data from channel
	for name := range channel // if the cahnnel is contain array/slice data, we also can make channel comsumed by this
}

Remember that when data is put into the channel but no one receives it, it will cause a deadlock

package main

var (
	channel = make(chan string) // remember that each channel can only take care one type of data
)

func main() {
	channel <- "harry duong" // put data into channel
}

Run the program we have this:

So always remember to consume the data from the channel! OK, Let’s see a simple example first:

package main

import (
	"fmt"
	"time"
)

func hello(done chan bool) { // different to chan<-int, which mean only send
	fmt.Printf("harry duong goroutine\n")
	time.Sleep(4 * time.Second)
	fmt.Printf("goroutine awake\n")
	done <- true
}
func main() {
	done := make(chan bool)
	go hello(done)
	<-done //this will help us no need for time sleep, main goroutine are blocked here, waiting for the channel pushs an elelement into it
	// time.Sleep(1 * time.Second)
	fmt.Println("*main goroutine")

}

run the example, this is what we got:


Below is the second example of using the channel to communicate between channels, you also can check it on my Github repository

package main

import "fmt"

func main() {
	number := 589
	sqrch := make(chan int)
	cubech := make(chan int)

	go calcSquares(number, sqrch)
	go calcCubes(number, cubech)

	squares, cubes := <-sqrch, <-cubech // this will stop the main go routine, waiting for two goroutine
	fmt.Println(squares + cubes)
}

func calcSquares(number int, squareop chan int) {
	sum := 0
	for number != 0 {
		digit := number % 10
		sum += digit * digit
		number /= 10
	}
	squareop <- sum
}

func calcCubes(number int, cubeop chan int) {
	sum := 0
	for number != 0 {
		digit := number % 10
		sum += digit * digit * digit
		number /= 10
	}
	cubeop <- sum
}

III. Conclusion

  • This is just the basics about the channel, I will have more posts about this so we can handle the channel as a pro player!

Leave a Reply

Your email address will not be published.