Concurrency in Go
Go has built-in concurrency primitives that make it easy to write concurrent programs. Go uses goroutines, which are lightweight threads that allow you to run multiple functions concurrently. You can create a goroutine using the go keyword.
func printNumbers() {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
func main() {
go printNumbers()
go printNumbers()
time.Sleep(time.Second)
}
In this example, we create two goroutines that print numbers from 0 to 9 concurrently. We use the time.Sleep() function to pause the main goroutine for a second to allow the other goroutines to finish.
No comments:
Post a Comment