In Go, a goroutine is a lightweight thread that allows a function to be executed concurrently with other functions. Goroutines are the building blocks of concurrent and parallel programming in Go.
Creating a goroutine is simple. You can use the go
keyword followed by a function call to create and run a new goroutine.
Here's an example:
main.go409 chars27 lines
In this example, we defined two functions printNumbers
and printLetters
, each printing a sequence of numbers and letters respectively with some delay using the time.Sleep
function to simulate some work being done.
In the main
function, we create two goroutines that execute these functions by using the go
keyword followed by a function call. We also call time.Sleep
to give the program enough time to run the goroutines.
When we run this program, we get the output:
main.go20 chars2 lines
Note that the printNumbers
and printLetters
functions are executed concurrently, with their output interleaved. This is because the two goroutines are executing simultaneously and independently, using the CPU cores available to run in parallel.
Concurrency in Go is achieved through goroutines, and communication between goroutines is achieved through channels. Together, they make it easy to write concurrent and parallel programs in an efficient and safe way.
gistlibby LogSnag