The task of distributing ten tasks between four threads and the task of using only four processors (I use the CPU here as a synonym for the kernel for simplicity) with your ten tasks are slightly different.
Four threads
Limiting the thread number to four does not guarantee that they will adhere to four processors and will not use others. OS allows you to shuffle your threads between all available processors as you wish. The only thing you can guarantee is that your program will not be able to use more than 50% of all CPU resources (given that you have eight processors).
But you are unlikely to be able to use these 50%. Despite the fact that your jobs are mainly processor-oriented, it is likely that they still need to read and write to memory from time to time. When a thread skips the cache on such reads / letters and expects the data to be delivered to the processor, this processor puts the thread on hold and can do some work on another thread. In your case, he has nothing to do and just sit idle until the data arrives. Thus, your processors are likely to be underused.
If you decide to go with this approach, you need to break your assignments into small tasks and hand them over to the performers, as @James Large said. You can use the WorkStealingPool with four threads (as suggested by @Alexey Soshin) or create a ten-thread pool and use Semaphore with four permissions and fairness set to true . In the latter case, your threads should use loops, get permissions at the beginning of each iteration, and release them at the end. Each iteration will be a small piece of work.
Four processors
There are mechanisms for assigning specific processors to work with your tasks.
At the process level on Linux, you can use special commands to bind the process to specific processors. This will allow you to create ten threads and allow the OS to perform all balancing on four processors.
At the thread level, you can try the Java Affinity library from OpenHFT. It allows you to associate threads with processors directly in your Java code. The problem is that ten threads cannot be shared between the four processors without a reminder, so it will be difficult to balance them.
source share