Fundamentals of Golang Concurrency
Golang is a statically typed, compiled programming language that has gained popularity for its simplicity, efficiency, and built-in support for concurrency. Concurrency is a fundamental concept in Golang, and it is achieved through the use of goroutines and channels.
Goroutines
Goroutines are lightweight threads of execution that are managed by the Golang runtime. They are created using the go
keyword, and they can be used to execute code concurrently. Goroutines are very lightweight, and they can be created and destroyed quickly, making them an efficient way to achieve concurrency in Golang applications.
func main() {
// Create a new goroutine
go func() {
// Code to be executed in the goroutine
fmt.Println("Hello from a goroutine!")
}()
// Wait for the goroutine to finish
time.Sleep(1 * time.Second)
fmt.Println("Main function completed")
}
Channels
Channels are a way for goroutines to communicate with each other. They are created using the make()
function, and they can be used to send and receive data between goroutines. Channels can be buffered or unbuffered, and they can be used to synchronize the execution of goroutines.
func main() {
// Create a new channel
ch := make(chan int)
// Send a value to the channel
go func() {
ch <- 42
}()
// Receive a value from the channel
value := <-ch
fmt.Println("Received value:", value)
}
Waitgroups
Waitgroups are a way to wait for a collection of goroutines to finish before continuing. They are created using the sync.WaitGroup
type, and they can be used to ensure that all goroutines have completed before the main function exits.
func main() {
// Create a new waitgroup
var wg sync.WaitGroup
// Add two goroutines to the waitgroup
wg.Add(2)
// Start the goroutines
go func() {
// Do some work
fmt.Println("Goroutine 1 completed")
wg.Done()
}()
go func() {
// Do some work
fmt.Println("Goroutine 2 completed")
wg.Done()
}()
// Wait for the goroutines to finish
wg.Wait()
fmt.Println("Main function completed")
}
By using goroutines, channels, and waitgroups, you can write concurrent Golang applications that are efficient, scalable, and easy to reason about.