Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing goroutines into the same thread

Tags:

go

goroutine

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?

like image 348
György Andrasek Avatar asked Dec 10 '09 11:12

György Andrasek


2 Answers

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.

like image 111
Nick Johnson Avatar answered Sep 29 '22 09:09

Nick Johnson


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

like image 24
Hai-Anh Trinh Avatar answered Sep 29 '22 10:09

Hai-Anh Trinh