-
Pthread CPU Affinity
Is there any way to run a POSIX thread with a predetermined cpu affinity? I am using pthread_setaffinity_np right now but the problem with that approach is that it only works with a thread that is already created. pthread_setaffinity_np simply moves the thread to another cpu if the current cpu that it is running on does not match the cpu mask passed in. If my pogram is constantly creating worker threads this seems like unnecessary overhead. You have no control over what cpu the thread actually starts on. Is there any way to set the cpu on which a POSIX thread will start as a result of calling pthread_create?
-
If you are creating threads often enough, consider using a thread-pool concept, where once a thread is finished with a task, it goes "back in the pool" and waits until it needs to process another task. So you would have a master thread (or API) for giving out tasks to threads in the pool. This avoids thread creation/destruction overhead.
The other option is to use pthread_attr_setaffinity_np() on an attribute object, which you use to create the threads.
gg
-
Yeah I am using the thread pool concept and it is working well. I tried using the pthread_setaffinity_np on a pthread_attr_t object but that didnt appear to work. When i called pthread_setaffinity_np on this struct before the thread was created using pthread_create and it returned EINVAL...
from man page:
EINVAL (pthread_setaffinity_np()) The affinity bit mask mask contains no
processors that are currently physically on the system and permitted to
the thread according to any restrictions that may be imposed by the
"cpuset" mechanism described in cpuset(7).
-
I called pthread_setaffinity_np on the thread_t struct.. not the attribute so what I described above is incorrect. Can you pass pthread_attr_t to pthread_setaffinity_np?
-
It's a different function - pthread_attr_setaffinity_np
gg
-
Well that's embarrassing.... somehow i completely overlooked that method in all of the reading I did :(