Go Goroutine
Goroutines are lightweight threads of execution in Go. They allow multiple functions to run concurrently within a single program, enabling efficient use of multi-core processors and scalable network services.
To create a new goroutine, use the go
keyword followed by the function call:
func sayHello() { fmt.Println("Hello, world!") } func main() { go sayHello() fmt.Println("Main function") }
In this example, sayHello
is executed concurrently with main
using the go
keyword. The sayHello
function will run in a separate goroutine and print "Hello, world!" while the main
function continues to execute.
Goroutines are lightweight, so you can create many of them without a significant performance overhead. They are also managed by the Go runtime, which schedules them automatically on available threads.
To synchronize communication between goroutines, you can use channels. Channels are a built-in mechanism in Go for passing messages between goroutines. Here's an example of using channels to communicate between two goroutines:
func worker(ch chan int) { for { num := <-ch fmt.Println("Worker received", num) } } func main() { ch := make(chan int) go worker(ch) for i := 0; i < 10; i++ { ch <- i } }
In this example, we create a channel of type int
using the make
function. We then create a goroutine that waits for values to be sent over the channel using the <-
operator. In the main
function, we send the numbers 0 to 9 to the channel using the ch <- i
syntax.
The worker function will receive each number as it is sent, and print "Worker received [number]" to the console.