Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guaranteed-invalid value for pthread_t?

Tags:

c

pthreads

PURPOSE: I want to create a thread pool: essentially an array of pthread_t values. I want to be able to terminate threads in progress, and to mark their pthread_t value as invalid, thus the slot is either available for a new thread, or is to be skipped during teardown. For client confidentiality reasons I can't discuss why this architecture was chosen.

PROBLEM: I know that direct pthread_t comparison is not permitted, and that pthread_equal() is the correct means to compare. However, I want for there to be some PTHREAD_T_INVALID value I can memcpy() into empty slots, both at initialisation and when they are vacated, and against which I can safely use pthread_equal().

The alternative, ugly and redundant, is to maintain a parallel array of bools indicating whether slots are in use. I would rather have a single source of truth: the pthread_t array.

I am aware of Is there an invalid pthread_t id?, but responses there skirt around the issue. I have the impression there is no direct answer to it, but since the original question was closed 14 years ago at time of writing, I was hoping there was a modern update that resolves it.

like image 260
Jon Green Avatar asked Jul 13 '26 18:07

Jon Green


2 Answers

Instead of an array of pthread_t, make an array of pthread_t *.

Array objects would initially be NULL. Allocate a pthread_t object before you create the thread and insert it in an empty slot in the array. When a thread ends, deallocate the object and set the array element to NULL.

like image 102
dbush Avatar answered Jul 15 '26 08:07

dbush


One possible solution I am considering is to use pthread_self() as a pthread_t value that is guaranteed not to be one of the spun-off threads.

like image 35
Jon Green Avatar answered Jul 15 '26 06:07

Jon Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!