Darkmer Darkmer - 2 years ago 82
Linux Question

Is it possible to only have threads with the id an even number?

I was doing some exercises with threads. In one such exercise a function ought to have different actions depending on the thread id. I got results as if all my threads were having as id's even numbers.

I tested separately using another variable, to which i gave both even and odd numbers, and it worked perfectly fine...

I was using

int x=pthread_self()
to get the thread id. Am I doing this wrong?

caf caf
Answer Source

The pthread_t type returned by pthread_self() is not guaranteed to even be a number (arithmetic type) at all - it could for example be a structure.

Even in the case where it is a number, it is entirely possible for it to always be an even number. In fact, this is the case using the glibc implementation of pthreads, where the pthread_t is the base stack address of the thread - because stacks are always going to be page-aligned, they won't just be even, they'll in fact always be divisible by 4096.

If you want to have threads perform different actions depending on their thread ID, you are best off allocating your own sequential numeric thread IDs to threads yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download