Concurrency is the ability of a computer program to have multiple execution paths that can run independently and simultaneously.
In Golang, concurrency is achieved through the use of goroutines and channels.
Goroutines
A goroutine is a lightweight thread of execution that can be created with the go
keyword, followed by a function call. For example:
go myFunction()
This will create a new goroutine that will execute the myFunction
function concurrently with the rest of the program. Goroutines are managed by the Go runtime, so they are very efficient and can be created and destroyed easily.
Channels
Channels are used to communicate between goroutines. They allow one goroutine to send data to another goroutine, allowing the two execution paths to synchronize and coordinate their actions. Channels are created with the make
keyword and data is sent to and received from channels using the <-
operator.
For example, the following code creates a channel that can be used to send integers:
ch := make(chan int)
To send a value on the channel, we use the <-
operator
ch <- 5