Junior — Middle
Kuidas toimub signaalide vahetamine kanalite kaudu programmeerimissüsteemis?
sobes.tech AI
Vastus AI-lt
In the Go (Golang) language, channels are used for exchanging signals and data between goroutines, ensuring synchronization and communication.
A channel is a typed conduit through which values can be sent and received. Sending and receiving on a channel blocks the goroutine until the other side is ready to accept or send data, allowing efficient synchronization of execution.
Example of signal exchange using a channel:
package main
import (
"fmt"
"time"
)
func worker(done chan bool) {
fmt.Println("Work started")
time.Sleep(time.Second) // simulate work
fmt.Println("Work finished")
done <- true // send completion signal
}
func main() {
done := make(chan bool)
go worker(done) // start goroutine
<-done // wait for completion signal
fmt.Println("Main function completed")
}
In this example, the done channel is used to transmit the completion signal of the worker goroutine. The main function blocks on reading from the channel until it receives the signal, allowing proper synchronization of execution.