Is there an invalid pthread_t id?

2019-01-13 17:23发布

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.

4条回答
够拽才男人
2楼-- · 2019-01-13 17:52

As suggested by Tony, you can use pthread_self() in this situation.

But do not compare thread_ts using == or !=. Use pthread_equal.

From the pthread_self man page:

Therefore, variables of type pthread_t can't portably be compared using the C equality operator (==); use pthread_equal(3) instead.

查看更多
We Are One
3楼-- · 2019-01-13 18:09

I recently ran into this same issue. If pthread_create() failed, I ended up with a undefined, invalid value stored in my phtread_t structure. As a result, I keep a boolean associated with each thread that gets set to true if pthread_create() succeeded.

Then all I need to do is:

void* status;
if (my_thread_running) {
  pthread_join(thread, &status);
  my_thread_running = false;
}
查看更多
别忘想泡老子
4楼-- · 2019-01-13 18:14

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-13 18:15

Unfortunately, on systems where pthread_t is a pointer, pthread_equal() can return equality even though the two args refer to different threads, e.g. a thread can exit and a new thread can be created with the same pthread_t pointer value.

查看更多
登录 后发表回答