Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an invalid pthread_t id?

Tags:

linux

pthreads

I would like to call pthread_join for a given thread id, but only if that thread has been started. The safe solution might be to add a variable to track which thread where started or not. However, I wonder if checking pthread_t variables is possible, something like the following code.

pthread_t thr1 = some_invalid_value; //0 ? pthread_t thr2 = some_invalid_value;  /* thread 1 and 2 are strated or not depending on various condition */ ....  /* cleanup */ if(thr1 != some_invalid_value)     pthread_join(&thr1);  if(thr2 != some_invalid_value)     pthread_join(&thr2); 

Where some_invalid_value could be 0, or an implementation dependant 'PTHREAD_INVALID_ID' macro

PS : My assumption is that pthread_t types are comparable and assignable, assumption based on

PPS : I wanted to do this, because I thought calling pthread_join on invalid thread id was undefinde behaviour. It is not. However, joining a previously joined thread IS undefined behaviour. Now let's assume the above "function" is called repeatedly. Unconditionnally calling pthread_join and checking the result might result in calling pthread_join on a previously joined thread.

like image 964
shodanex Avatar asked Jun 08 '11 09:06

shodanex


People also ask

What data type is pthread_t?

A thread ID is represented by the pthread_t data type. Implementations are allowed to use a structure to represent the pthread_t data type, so portable implementations can't treat them as integers. Therefore, a function must be used to compare two thread IDs.

What does pthread_create return?

pthread_create() returns zero when the call completes successfully.

What is Pthread_join in C?

The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread.


1 Answers

Your assumption is incorrect to start with. pthread_t objects are opaque. You cannot compare pthread_t types directly in C. You should use pthread_equal instead.

Another consideration is that if pthread_create fails, the contents of your pthread_t will be undefined. It may not be set to your invalid value any more.

My preference is to keep the return values of the pthread_create calls (along with the thread IDs) and use that to determine whether each thread was started correctly.

like image 121
qbert220 Avatar answered Sep 18 '22 00:09

qbert220