[fpc-pascal] CPU affinity of TThread descendants

David W Noon david.w.noon at ntlworld.com
Tue Jan 20 22:20:43 CET 2009

On Tue, 2009-01-20 at 11:34 +0100, Vinzent Höfler wrote:

> -------- Original-Nachricht --------
> > Datum: Tue, 20 Jan 2009 09:07:54 +0100 (CET)
> > Von: Michael Van Canneyt <michael at freepascal.org>
> > No CPU affinity is imposed as far as I know; 
> > Under Linux, this is not possible, at least I've never heard of such a
> > call.
> sched_set_affinity()
> sched_get_affinity()

Correct spelling:


> (Now you've heard. ;)

There are also pthread_setaffinity_np() and pthread_getaffinity_np(),
where the "_np" suffix is a mnemonic for "non-portable".

> The default for the CPU masks should be all 1s though, so the scheduler
>  should distribute the threads evenly to all available CPUs. But... AFAIR
>  the affinity mask is inherited by child processes, so maybe the main
>  thread already has some affinity mask set (well, I don't see no reason
>  why it should, but you never know).
> So for the original poster I'd suggest inserting a sched_get_affinity()
>  call and check the resulting bit mask. If that's not all 1s, one should
>  investigate the reason... if it is, then maybe the scheduler detects too
>  many dependencies between the threads, so it doesn't distribute the
>  thread on both CPUs, or maybe there's one totally different reason for
>  the behaviour...

I have checked the CPU masks for all threads and the first byte is
always 0x03, which indicates that both CPUs can be considered for
dispatching the thread.

I have noticed one thing that might shed a little light on the topic:
whenever I use a pipe for the output and I allow the pipe to stall with
a full buffer, after execution is resumed the program sometimes restarts
on the other CPU, but again all threads run on the same CPU. This would
indicate to me that the child threads are tightly associated with the
parent thread, as far as CPU selection goes.

I will reimplement my code in C++ using wxWidgets and its wxThread
class, and see what behaviour that produces.

I might also reimplement the code in C, using the pthread_??? family of
API calls in their raw state. This could be a bit ugly, as the code is
decidedly object oriented.

As it appears that this issue is at a lower level than the TThread
class, we might need to examine the BeginThread() function of the RTL.
However, it could be attributable to the threading library I use with
Linux (NPTL, in my case).

I shall report back with whatever I find.


Dave  [RLU #314465]
david.w.noon at ntlworld.com (David W Noon)

More information about the fpc-pascal mailing list