Getting a grip on Go's Goroutines and Channels (Part 1)

Go is a concurrent programming language, to understand what concurrency is check here: https://ikeoha.com/post/concurrency-vs-parallelism-for-the-layman-my-people/

Go achieves this said concurrency with the use of goroutines.

Goroutines simply put are lightweight threads, what does this mean for you? Well it means that functions in go can easily run concurrently beside other functions. These goroutines are extremely lightweight, more lightweight than native threads, as a result of that, numerous goroutines can be spawned with little to no cost.

To Start a Goroutine in Golang is as simple as adding the keyword go to the beginning of the function call.

Example of this:


func helloWorld() {

    log.Println(“I’m Saying hello world here”)

} 



// this is a goroutine

go helloWorld()



// sometimes too you'll see this

// the code below is an anonymous function or a lambda function in some other languages as it doesn’t have a name

go func() {

\    // do something

}()

All Go code has one Goroutine right off the bat with the main function. According to my research it is what is called the main thread.

Now Goroutines need a way to communicate with each other that’s where channels come in handy.

Must Know about channels

A channel can be a receiving channel, A sending channel or it can be both.


// Examples of channels



// this is a read only channel, data can’t be sent to it

// the data must be bool data type

Channel := make(<-chan bool)



// this is a send only channel, data can only be sent out of this channel

// the data must be bool data type

Channel := make(chan<- bool)



// this is both a send and receive channel

// the data must be bool data type

Channel  := make(chan string)



Let me walk you through how you would send data to a channel



// first create the channel

// note this is a channel which can send and receive data

Channel  := make(chan string)



// send data to channel

Channel <- “hello world”



// receive data from a channel

channelReceiver := <- Channel



// NOTE THE DIRECTION OF THE ARROWS

You should definitely read my next article on this because just this knowledge alone can take you far but not far enough