Channels serve as pipes for communication between concurrent goroutines. They allow one goroutine to send values and another goroutine to receive those values. By default, sending and receiving operations block until both the sender and receiver are ready. This feature enabled us to wait for the "unbuffered channel" message at the end of our program without needing any additional synchronization mechanisms. Buffered channels can hold a limited number of values without requiring an immediate receiver.
2 snippets
package main
import (
"fmt"
"time"
)
func print(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
// Synchronous function call
print("synchronous call")
// Asynchronous function call
// To run this function in a goroutine, use go f(s)
// This new goroutine will execute concurrently with the calling main goroutine
go print("asynchronous call")
// Goroutine can also be execute as an anonymous function
go func(msg string) {
fmt.Println(msg)
}("asynchronous anonymous call")
// Two previous function calls are now running asynchronously in separate goroutines
// Wait for them to finish
time.Sleep(time.Second)
fmt.Println("done")
}
// $ go run main.go
// synchronous call : 0
// synchronous call : 1
// synchronous call : 2
// asynchronous anonymous call
// asynchronous call : 0
// asynchronous call : 1
// asynchronous call : 2
// doneHere is an example of goroutines in Golang.
0 Burnfires
0
Snippets46
Categories0
Tags62
Users3


