CSE224 - Go Concurrent Programming
Introduction
Go Routines
Traditionally, people used OS-level threads for concurrency, but threads are heavyweight. Go introduced goroutines, which are
- Very cheap in terms of memory
- Managed by the Go runtime, not the OS
- Can be created in large numbers
Go uses an internal scheduler that maps many goroutines onto fewer OS threads using something called the M:N model (many goroutines on few threads). The scheduler runs in user space — no need to ask the operating system every time. As a result, go routines is like a user-level thread.
go sayHello() // create a go routineChannel
A channel is a way for goroutines to communicate and synchronize with each other. It’s like a pipe.
ch := make(chan string)
go func() {
ch <- "hello"
}()
msg := <-ch
fmt.Println(msg) // prints: helloChannels can be synchronous or buffered:
- Synchronous: No buffer. The sender waits until a receiver is ready.
ch := make(chan int)
go func() {
fmt.Println("Sending...")
ch <- 42 // block until some routine receive data
fmt.Println("Sent")
}()
x := <-ch // block until some data is available
fmt.Println("Received", x)- Buffered: Has space to hold values. Sender doesn’t wait until buffer is full.
ch := make(chan int, 2)
ch <- 1
ch <- 2
// Can send twice before it blocksCSE224 - Go Concurrent Programming
http://example.com/2025/05/10/CSE224/go-concurrent/