Published on

Goroutine and Channel Explained

Goroutine and Channel Explained

Go: Goroutine and Channel

Two of the key concepts in Go are Goroutines and Channels, which are used for concurrent programming and communication between Goroutines. In this article, we will explain Goroutines and Channels in Go with examples.

What are Goroutines in Go?

A Goroutine is a lightweight thread of execution that runs concurrently with other Goroutines in the same program. They are much cheaper to create and manage compared to threads in other programming languages, and they are designed to handle many Goroutines running concurrently with minimal overhead.

Why Use Goroutines in Go?

Goroutines are used in Go to handle concurrency and to allow multiple tasks to run simultaneously. They make it easy to write concurrent programs that can handle a large number of Goroutines efficiently. They are also used to perform multiple tasks concurrently, such as sending and receiving data between Goroutines.

How to Create a Goroutine in Go?

A Goroutine is created by calling the go keyword followed by a function. Here's an example:


package main

import (
	"fmt"
	"time"
)

func printNumbers() {
	for i := 0; i < 10; i++ {
		fmt.Println(i)
		time.Sleep(1 * time.Second)
	}
}

func main() {
	go printNumbers()
	fmt.Println("Main function")
	time.Sleep(11 * time.Second)
}

In this example, the printNumbers function is run as a Goroutine. It runs concurrently with the main function, and both functions are executed simultaneously.

What are Channels in Go?

Channels in Go are used to communicate between Goroutines. They allow Goroutines to send and receive data, and they provide a synchronization mechanism to ensure that data is transmitted and received in the correct order. Channels are created using the make function, and they are typed, which means that they can only send and receive data of a specific type.

How to Use Channels in Go?

Channels in Go are used to send and receive data between Goroutines. Here's an example:

package main

import "fmt"

func sum(a []int, c chan int) {
	sum := 0
	for _, v := range a {
		sum += v
	}
	c <- sum
}

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

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

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