← Back to context

Comment by tuetuopay

5 days ago

Overall great article, applicable to other languages too.

I'm curious about the Goroutine pinning though:

    // Pin goroutine to specific CPU
    func PinToCPU(cpuID int) {
        runtime.LockOSThread()
        // ...
        tid := unix.Gettid()
        unix.SchedSetaffinity(tid, &cpuSet)
    }

The way I read this snippet is it pins the go runtime thread that happens to run this goroutine to a cpu, not the goroutine itself. Afaik a goroutine can move from one thread to another, decided by the go scheduler. This obviously has some merits, however without pinning the actual goroutine...

`runtime.LockOSThread()` will pin the current goroutine to the os thread that its currently running on

  • Oooh, that's what is happening. I assumed it locked some structure about the thread while touching it, to prevent races with the runtime. That's what I get for not RTFM'ing (in fairness, why Lock and not Pin, when both of these words have pretty well defined meanings in programming?)

    Thank you

  • And prevents other goroutines from running on that thread. I think that’s crucial.