0

I recently wrote some code[1][2] that tried using JNA to make calls to sched_setaffinity in an attempt to set the affinity of the process to a particular core. The first argument of the function sched_setaffinity is the process id.

Calling the function with pid as 0(referring to the process itself) works fine. However, I'd like to be able to set the affinity on a thread id basis rather than the process. Is there any way I could do that?

  1. https://github.com/eQu1NoX/JavaThreadAffinity/blob/master/src/com/threads/ctest.c
  2. https://github.com/eQu1NoX/JavaThreadAffinity/blob/master/src/com/threads/ThreadAffinity.java

1 Answers1

0

There is a function called pthread_setaffinity_np that can set the CPU affinity mask of the thread thread to the CPU set pointed to by cpuset.

cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);

pthread_t current_thread = pthread_self();    
pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);

This piece of code can set the a thread to the core(represented by core_id).

As far as I know, a Java Thread is not always matched to a thread in OS. So I'm not quite sure whether this piece of native code can help you.

StarPinkER
  • 14,081
  • 7
  • 55
  • 81