Forcing goroutines into the same thread

拟墨画扇 提交于 2019-12-09 16:24:11

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/1880262/forcing-goroutines-into-the-same-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!