Is there a way to ensure that a goroutine will run only in a specific OS thread? For example, when GUI operations must run in the GUI thread, but there might be multiple goroutines running GUI code.
GOMAXPROCS(1)
does the job technically, but that defeats the purpose of multithreading.
LockOSThread()
works too, but that prevents any other goroutine from running in that thread as well.
Is there a way to do this, or must everything that requires the same thread also run in the same goroutine?
To the best of my knowledge, not currently. I think the 'go-like' way to do this would be to write a Goroutine that runs in the GUI thread and services requests from other goroutines sent in over a channel. For example, you could have it read from a channel that accepts function pointers, and execute those functions.
Why do you want to do this? I believe runtime.LockOSThread()
is necessary if you are creating a library binding from C code which uses thread-local storage. Otherwise, just let the scheduler multiplex the goroutines for you.
And note that runtime.LockOSThread()
only prevents other goroutines from running in that thread until you call runtime.UnlockOSThread()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With