CSE224 - Go Concurrent Programming

Introduction

Go Routines

Traditionally, people used OS-level threads for concurrency, but threads are heavyweight. Go introduced goroutines, which are

  1. Very cheap in terms of memory
  2. Managed by the Go runtime, not the OS
  3. 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.

1
go sayHello() // create a go routine

Channel

A channel is a way for goroutines to communicate and synchronize with each other. It’s like a pipe.

1
2
3
4
5
6
7
8
ch := make(chan string)

go func() {
ch <- "hello"
}()

msg := <-ch
fmt.Println(msg) // prints: hello

Channels can be synchronous or buffered:

  1. Synchronous: No buffer. The sender waits until a receiver is ready.
1
2
3
4
5
6
7
8
9
10
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)
  1. Buffered: Has space to hold values. Sender doesn’t wait until buffer is full.
1
2
3
4
ch := make(chan int, 2)
ch <- 1
ch <- 2
// Can send twice before it blocks

CSE224 - Go Concurrent Programming
https://thiefcat.github.io/2025/05/10/CSE224/go-concurrent/
Author
小贼猫
Posted on
May 10, 2025
Licensed under