Understanding runtime.LockOsThread

1,300 views
Skip to first unread message

Adam

unread,
Sep 10, 2015, 7:09:16 AM9/10/15
to golang-nuts
To understand go scheduler I wrote this simple code https://gist.github.com/anonymous/bc2d650c736f195be358. Without the line where I call runtime.LockOsThread() it works as I expect, ie I can run this code on 2 cores and it will block on CPU bound goroutines, this is because there is no place where context switch could happen. Also no IOBound goroutine will be run. 

Now as the docs states:

LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.


From my understanding IOBound goroutine should be bind to its own dedicated core so no CPUBound goroutine should still CPU from it and allow it to run, but it doesn't happen. Why?

Bonus questions, what are your best practices on writing go applications performing hard CPU bound operations with need of having low latency for IO tasks also. My solution would be to create a pool of CPU bound workers binded to its own CPUs so other IO tasks could perform with no blocking, though it doesn't seems to me like it is the go way.

Vasko Zdravevski

unread,
Sep 10, 2015, 10:06:10 AM9/10/15
to golang-nuts, adam.dr...@gmail.com
Hi Adam,

I and many others have asked a similar question. If you search the discussion group, you'll see quite a few threads on this.


For me the thing that helped me grasp how to approach this was reading the Go Scheduler design doc. There is even a section specifically on LockOSThread in this doc.


The short answer is that LockOSThread locks your goroutine to an OS Thread, but that thread isn't locked to 'proc'. In the design doc parlance, your G is locked to an M, but not a P. G(oroutine), M(OS Thread), P(Procs - Go runtimes number of parallel running threads executing Go code up to GOMAXPROCS).

Hope this helps,
Vasko.
Reply all
Reply to author
Forward
0 new messages