Ring buffer — counter pointers and mirror indexing

聊聊ringbuffer

A ring buffer (circular queue) joins head and tail: read/write cursors advance around a fixed slice instead of shifting elements on every dequeue.

The payoff: after a dequeue you do not slide the rest of the queue forward; the next enqueue overwrites the freed slot.

Below is a common pattern—separate read/write counters—with a diagram-friendly walkthrough. Code is adapted from chanx ringbuffer.

Counter-based implementation

Skim the code first; a picture afterward makes the flow obvious.

Read More

Recursive orDone — goroutine leaks and infinite recursion with three channels

二分递归版or-channel模式的问题

While fixing benchmarks for “two ways to implement orDone”, I found bugs in the binary-recursive version — mainly goroutine leaks. See also learning orDone the hard way.

Read More

sync.Cond by example — wait, signal, and broadcast

举例来学cond原语

I recently read Ma Que’s Go Concurrency in Practice course and plan to revisit the concurrency primitives with small examples. Today: sync.Cond.

Cond is for wait/notify patterns: goroutines block in Wait while a condition is false; when it becomes true, Signal wakes one waiter or Broadcast wakes all of them.

Picture ten athletes on the track — the starter fires the gun only after everyone is ready:

Read More

Go runtime — the 24-byte size class and an 8-byte allocation win

一个8bytes的内存优化

While reading Dave Cheney’s post, I noticed a benchmark that highlights an eight-byte allocation improvement.

1
2
3
4
5
6
7
8
9
func BenchmarkSortStrings(b *testing.B) {
s := []string{"heart", "lungs", "brain", "kidneys", "pancreas"}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var ss sort.StringSlice = s
var si sort.Interface = ss
sort.Sort(si)
}
}

Read More

Go sync.Mutex — atomics, barriers, and starvation mode

Dig101-Go之深入理解mutex

Dig101: dig more, simplified more and know more

sync.Mutex is Go’s mutex — simple to use, but how is it implemented, and why those choices?

A few questions, no wall of assembly — just enough to read the source later with context.

Read More

Go reflect — unexported struct fields from outside the package

Go之如何操作结构体的非导出字段

Dig101: dig more, simplified more and know more

Lowercase struct fields are unexported — other packages cannot name them in ordinary code. Reflection can still reach them. Here is how reflect does it from outside the defining package.

Read More

Go — pointer parameters, assignment vs dereference

Dig101-Go之如何在函数内修改指针指向

Dig101: dig more, simplified more and know more

A small but common question: how can a function change a pointer (parameter or receiver) so the effect is visible outside the function?

Straight to code — does this work?

1
2
3
4
5
6
7
8
9
type ArgType struct {
A string
b int
}

func modifyPointerArg1(arg *ArgType) {
arg = &ArgType{"arg1", 1}
fmt.Println("inside modifyPointerArg1:", arg)
}

Read More