πŸ”ΉGo Routine and Channel

Describe about Go routine and Channel

Go Routine

It is the way that we call function with concurrency in Go that ensuring the response got return and synchronized by Channel or WaitGroup .

Channel

It is similar to queue that receive the response from go routine function by sender so It will ensure the data is synchronized before end the process.

There are 2 type of channels

  1. Unbuffered channels

  2. Buffered channels

Unbuffered Channel

When you create an unbuffered channel, it has a capacity of zero. It mean when the sender send the data to channel it will block the operation until the receiver ready to receive it and the receiver will wait until the sender ready to send data as well.

Example

	start := time.Now()

	ch := make(chan string)

	go func() {
		time.Sleep(3 * time.Second)
		ch <- "finish process"
	}()

	response := <-ch

	// response
	fmt.Println(response)

	// time took
	fmt.Println(time.Since(start))
	
// output
finish process
3.0012505s

Buffered Channel

When you create an buffered channel, It has a specified capcity greater than zero.

It can hold a certain numbers of the values in the channel before blocking then the sender is able to send data to buffer until it full. the difference between unbuffered channel and buffered channel , when the data was sent to channel it will block the operation for receiver so the sender is not able to send the data for "b" because deadlock.

// Unbuffered Channel
        ch := make(chan string)
        ch <- "a"
	ch <- "b"

	// response
	response := <-ch
	fmt.Println(response)
	response2 := <-ch
	fmt.Println(response2)
	
//output 
fatal error: all goroutines are asleep - deadlock!	
// Buffered Channel
        ch := make(chan string, 2)
        ch <- "a"
	ch <- "b"

	// response
	response := <-ch
	fmt.Println(response)
	response2 := <-ch
	fmt.Println(response2)
	
//output 
a
b
54.708Β΅s

// For this scenario if we add 
// ch <- "c" after line ch <- "b"
// it will error because the buffer is full.

WaitGroup

Wait groups are created using the sync package, and they provide three essential methods: Add(), Done(), and Wait().

  • Add() is used to add the number of goroutines that need to be waited upon.

  • Done() is called by each goroutine when it finishes its work, decrementing the internal counter of the wait group.

  • Wait() is used to block the execution of the goroutine until all the goroutines have called Done().

Example


var wg sync.WaitGroup

func main() {
	wg.Add(2)
	go func() {
		fmt.Println("process1")
		wg.Done()
	}()
	go func() {
		fmt.Println("process2")
		wg.Done()
	}()
	wg.Wait()
}

Last updated