是否有可能强制执行例程在特定的CPU上运行? [英] is it possible to force a go routine to be run on a specific CPU?

查看:142
本文介绍了是否有可能强制执行例程在特定的CPU上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于go包的运行时,并且看到我可以在其他(func GOMAXPROCS(n int))中设置可用于运行我的程序的CPU单元的数量。我可以强制一个goroutine在我选择的特定CPU上运行吗?

解决方案

在现代Go中,我不会将goroutines锁定到线程以提高效率。 Go 1.5 增加了goroutine调度关联性,以最大限度地减少goroutine在OS线程之间切换的频率。并且必须权衡CPU之间剩余迁移的成本,以避免用户模式调度程序的好处,从而避免上下文切换到内核模式。最后,当转换成本是一个真正的问题时,有时更好的焦点是改变你的程序逻辑,所以它需要更少的切换,就像通过批量工作而不是单个工作项目进行通信一样。



但即使考虑了所有这些,有时候你只需要锁定一个goroutine,就像C API需要的那样,我会假设情况如下。




如果整个程序以 GOMAXPROCS = 1 运行,那么通过调用来设置CPU关联相对简单从schedutils包到taskset实用程序



如果 GOMAXPROCS> 1 ,因为然后 goroutines在运行时在OS线程之间迁移。实际上,James Henstridge指出你可以使用 runtime.LockOSThread() 来防止你的goroutine迁移。尽管如此,我不知道任何Go stdlib函数会在您将goroutine锁定之后设置当前线程的CPU关联。您可能可以使用cgo并调用 pthread_setaffinity_np ,因为显然 Go使用pthreads在cgo模式下。由于我们正在讨论系统调用,所以细节会因操作系统而异。



(如果您的整个程序是纯Go(没有C链接),则可能需要调用 sched_setaffinity 通过 syscall 模块获得一个零 pid 参数,但这会非常棘手。)


I am reading about the go package "runtime" and see that i can among other (func GOMAXPROCS(n int)) set the number of CPU units that can be used to run my program. Can I force a goroutine to be run on a specific CPU of my choice?

解决方案

In modern Go, I wouldn't lock goroutines to threads for efficiency. Go 1.5 added goroutine scheduling affinity, to minimize how often goroutines switch between OS threads. And any cost of the remaining migrations between CPUs has to be weighed against the benefit of the user-mode scheduler avoiding context switches into kernel mode. Finally, when switching costs are a real problem, sometimes a better focus is changing your program logic so it needs to switch less, like by communicating batches of work instead of individual work items.

But even considering all that, sometimes you simply have to lock a goroutine, like when a C API requires it, and I'll assume that's the case below.


If the whole program runs with GOMAXPROCS=1, then it's relatively simple to set a CPU affinity by calling out to the taskset utility from the schedutils package.

I had thought you were out of luck if GOMAXPROCS > 1 because then goroutines are migrated between OS threads at runtime. In fact, James Henstridge points out you can use runtime.LockOSThread() to keep your goroutine from migrating. I don't know of any Go stdlib function to set the current thread's CPU affinity once you've locked a goroutine to it, though. You might be able to use cgo and call pthread_setaffinity_np, since apparently Go uses pthreads in cgo mode. Since we're talking about system calls, details will vary by OS.

(If your whole program is pure Go (no C linked in), it may work to call sched_setaffinity with a zero pid parameter via the syscall module. But that's going to be tricky.)

这篇关于是否有可能强制执行例程在特定的CPU上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆