简体   繁体   English

如何设置Java线程的cpu核心关联?

[英]How to set a Java thread's cpu core affinity?

I searched previous postings on the similar topic but could not find a befitting answer therefore asking this question. 我搜索过类似主题的先前帖子,但找不到合适的答案因此问这个问题。 Your help in answering it is highly appreciated. 非常感谢您的回答。

I am aware of setting a process's affinity to a particular CPU core by taskset command in Linux. 我知道在Linux中通过taskset命令设置进程对特定CPU核心的亲和力。 But I want to set a Java thread's affinity to a particular cpu core so that other threads belonging to the same process can run on all remaining cores. 但我想设置一个Java线程与特定cpu核心的亲和力,以便属于同一进程的其他线程可以在所有剩余的核心上运行。 For example if I have a process containing 10 threads with 4-core machine, I would like to reserve core-1 for a thread and let remaining 9 threads run on remaining 3-cores. 例如,如果我有一个包含10个线程和4核机器的进程,我想为一个线程保留core-1,并让剩余的9个线程在剩余的3个核心上运行。 Can it be done and how? 可以这样做吗?

Thanks Sachin 谢谢萨钦

Say 2241 is the pid of your java process. 说2241是你的java进程的pid。 Run: 跑:

jstack 2241

This gives you a list of threads. 这为您提供了一个线程列表。 Find yours there and note the nid field. 在那里找到你的并注意nid字段。 Say nid=0x8e9, which converts to base 10 as 2281. Then run: 说nid = 0x8e9,它转换为基数10为2281.然后运行:

taskset -p -c 0 2281

Done. 完成。

Unfortunately, you cannot assign Java Threads to a specific core. 遗憾的是,您无法将Java线程分配给特定核心。 What you can do, however, is set Thread Priorities to prioritize the threads (assuming that this would accomplish the same thing) 但是,您可以做的是设置线程优先级以确定线程的优先级(假设这将完成相同的事情)

Alternatively, you could use JNI, but that would be completely overkill. 或者,您可以使用JNI,但这将是完全矫枉过正的。

Remember the Java application that your running is actually running in a JVM which is in turn running on the OS. 记住您的运行实际在JVM中运行的Java应用程序,而JVM又在操作系统上运行。 For you to be able to directly interact with the CPU you'd need a low level programming language (eg C). 为了能够直接与CPU交互,您需要一种低级编程语言(例如C)。

As suggested in another answer you can use JNI to interact with lower level language (like C) to do what you want however you'd have to delegate concurrency (threads managed within that lower level langaguge) to it... 正如在另一个答案中所建议的那样,您可以使用JNI与较低级别的语言(如C)进行交互以执行您想要的操作,但是您必须将并发(在较低级别的langaguge中管理的线程)委派给它...

You can do that in plain Java using JNA. 您可以使用JNA在普通Java中执行此操作。 There is no need to use taskset. 没有必要使用任务集。 Just remember that thread affinity is pointless unless you have previously isolated the core from kernel/user threads and hardware interrupts. 请记住, 线程关联是没有意义的,除非您之前已将核心与内核/用户线程和硬件中断隔离开来。 I am affiliated with Coral Blocks which has developed CoralThreads which does exactly that. 我隶属于Coral Blocks,它开发了CoralThreads ,就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM