tags:

views:

178

answers:

2

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?

+5  A: 

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.

Nick Johnson
-1 Your answer to "Is there a way to ensure that a goroutine will run only in a specific OS thread?" is "write a Goroutine that runs in the GUI thread"? How is this supposed to help me?
Jurily
You already pointed out that LockOSThread lets you lock the goroutine to a specific thread. Simply do so for the GUI thread.
Nick Johnson
+1  A: 

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().

Amadeus