Go
ch := make(chan int) // Creates an unbuffered channel for integers
ch := make(chan string, 10) // Creates a buffered channel for strings with a capacity of 10
func main() { // Unbuffered channel unbufferedCh := make(chan int) go func() { fmt.Println("Sending 10 to unbuffered channel...") unbufferedCh <- 10 // This will block until main receives fmt.Println("Sent 10 to unbuffered channel.") }() fmt.Println("Receiving from unbuffered channel...") val := <-unbufferedCh fmt.Printf("Received %d from unbuffered channel.\n", val)
}
When a Go routine does not print expected logs, the primary reason is often that the main Go routine exits before the concurrently running Go routine has a chance to execute or complete its tasks, including printing.
package main
import "fmt"
func main() {
done := make(chan bool)
go func() {
fmt.Println("Hello from goroutine!")
done <- true // Signal completion
}()
<-done // Wait for the signal
fmt.Println("Main function done.")
}
No comments:
Post a Comment