Quote:
Is there a way to change these attributes "on-the-fly", meaning, after the thread is created?
|
I've never used this feature, but I'm going to stick my neck out and say "no".
The various functions in the POSIX threads interface are named in a carefully consistent way. The feature in which you're interested is reflected in the API with that same careful consistency.
If there had been any way specifically to change the CPU affinity on the fly, one would expect
<pthread.h> to name additional functions whose names include "
affinity". But there are none.
Or if there were a way to apply thread attributes to an already-existing thread, one would expect
<pthread.h> to name an additional function to do so, and its name would end in "
_np", since all
non-
portable functions in
<pthread.h> have names that end thus. But I've looked at each non-portable function declaration in that file, and none of them do this.
But you don't need that capability. If you have
n different combinations of affinities you want a given thread to switch between, just define
n threads, with all of them but one waiting on its own condition variable which (when signaled) indicates that this thread has the currently desired affinity. When it comes time to switch affinities, the thread which is currently running should signal the appropriate condition for the desired thread, and then itself wait on its own condition, to be signaled if it's ever the case in the future that its own affinity is appropriate.
Additional care must be taken to allow such waiting threads to be allowed to continue, but go straight to exit instead of doing normal processing; otherwise you'd never be able to join those threads later, if you want to do so.
If you're using
pthread_setspecific() , then allocate a block of data to be shared by these threads, and let each thread's specific data point to that shared data. You won't need to use mutual exclusion on any of that data, because only these threads (which are for identical work, except that the affinities differ) will be using that data, and only one of these threads will be working at any given time.
Hope this helps.