Junior — Middle
What is the mechanism of multitasking used in channels for data exchange between threads or processes?
sobes.tech AI
Answer from AI
In Go, the concurrency mechanism based on channels is founded on the concept of CSP (Communicating Sequential Processes). Channels allow goroutines (lightweight threads) to safely exchange data, synchronizing execution without explicit locks.
A channel acts as a queue where one goroutine can send data, and another can receive. Sending and receiving block the goroutine until the other side is ready for the operation, ensuring synchronization and preventing data races.
Example:
ch := make(chan int)
// Sending data in a goroutine
go func() {
ch <- 42 // blocks until someone reads
}()
// Receiving data
val := <-ch // blocks until data appears
fmt.Println(val) // 42
Thus, channels implement a cooperative multitasking mechanism where goroutines interact through message exchange rather than shared memory.