πΉ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
Unbuffered channels
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
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.
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 calledDone()
.
Example
Last updated