Go 1.0: Concurrency via Channels and CSP
Google's "Go" language has finally reached stability. While other languages are bolting threads and callbacks onto existing frameworks, Go was built from the ground up for the multi-core era. The philosophy is simple: Communicating Sequential Processes (CSP).
Goroutines: Not Quite Threads
A goroutine is a lightweight thread managed by the Go runtime. You can spawn millions of them because they start with a tiny stack (about 2KB) that grows and shrinks as needed. The scheduler multiplexes these goroutines onto a small number of OS threads.
The Channel: The Pipe of Go
Channels are the pipes that connect goroutines. They provide a way for goroutines to synchronize and exchange data without explicit locks or condition variables.
package main
import "fmt"
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("worker %d processing job %d\n", id, j)
results <- j * 2
}
}
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// Start 3 workers
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// Send jobs
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// Collect results
for a := 1; a <= 5; a++ {
<-results
}
}
Select: The Multi-Plexer
The select statement lets a goroutine wait on multiple communication operations. It’s like a switch statement but for channels. It blocks until one of its cases can run, then it executes that case.
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
case <-time.After(time.Second):
fmt.Println("timeout")
}
The scheduler (M:P:G)
Inside the Go 1.0 runtime, the scheduler uses an M:P:G model. M represents an OS thread, P represents a processor (context for scheduling), and G represents a goroutine. If a goroutine makes a blocking system call (like reading a file), the scheduler "hand-offs" the other goroutines on that P to a new M, ensuring that your CPU cores stay busy even when some threads are blocked. This is why Go handles I/O-bound tasks so much better than traditional thread-per-request models.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development