强制goroutine在同一线程中运行

huangapple go评论94阅读模式
英文:

Forcing goroutines into the same thread

问题

有没有办法确保goroutine只在特定的操作系统线程中运行?例如,当GUI操作必须在GUI线程中运行时,但可能有多个goroutine运行GUI代码。

GOMAXPROCS(1)在技术上可以实现这个目标,但这违背了多线程的目的。

LockOSThread()也可以实现,但这也会阻止其他goroutine在该线程中运行。

有没有办法做到这一点,或者需要在同一个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?

答案1

得分: 8

据我所知,目前还没有。我认为实现这个的“类似Go”的方式是编写一个在GUI线程中运行的Goroutine,并处理通过通道发送的其他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.

答案2

得分: 3

为什么你想要这样做?如果你正在从使用线程本地存储的C代码创建库绑定,我相信runtime.LockOSThread()是必要的。否则,只需让调度器为你多路复用goroutine。

请注意,runtime.LockOSThread()只会阻止其他goroutine在该线程上运行,直到你调用runtime.UnlockOSThread()

英文:

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

huangapple
  • 本文由 发表于 2009年12月10日 19:05:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/1880262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定