Java Multithreading - Assign threads to processor cores

前端 未结 7 1439
[愿得一人]
[愿得一人] 2020-12-18 09:42

I am writing an application in java which involves parallel computing. My question is how can I explicitly assign threads to cores? What is the programming logic for it?

相关标签:
7条回答
  • 2020-12-18 10:26

    The OS manages what threads are processed on what core. You will need to assign the threads to a single core in the OS.

    For instance. On windows, open task manager, go to the processes tab and right click on the java processes... then assign them to a specific core.

    That is the best you are going to get.

    you can assign thread priority as per your requirement

    0 讨论(0)
  • 2020-12-18 10:34

    You cannot assign threads to cores.

    1. Java7's fork/join framework addresses exactly the same problem. Automatically though (It will be designed for multi-core processors).

    2. What you can do is to set Thread priority to prioritize your threads, if that's what you want to achieve.

    3. JNI might be another direction to export, but an overkill I guess. You can look at Peter Lawrey's Java-Thread-Affinity which uses JNI (I haven't used it).

    0 讨论(0)
  • 2020-12-18 10:36

    As said, the JVM won't let you. But first, you should ask yourself why you're thinking about assigning threads to cores. This is probably not what you want to do.

    The Executor class is used to schedule medium-sized "grains" of computation without incurring the overhead of creating too many threads. You may also want to try using parallel branches for a much more fine-grained scheduling, here are some code samples: http://www.ateji.com/px/codesamples.html

    0 讨论(0)
  • 2020-12-18 10:41

    I think the simple answer here would be you just can't.

    0 讨论(0)
  • 2020-12-18 10:46

    You can't. See this article. The JVM will delegate this to the OS, which will handle it for you.

    0 讨论(0)
  • 2020-12-18 10:46

    See Java Thread Affinity project.

    Lock to CPU

    try (AffinityLock al = AffinityLock.acquireLock()) {
        // do some work while locked to a CPU.
    }
    

    Lock core:

    try (AffinityLock al = AffinityLock.acquireCore()) {
        // do some work while locked to a CPU.
    }
    
    0 讨论(0)
提交回复
热议问题