【发布时间】:2021-11-30 16:01:13
【问题描述】:
我想为给定的线程 ID 调用 pthread_join,但前提是该线程已启动。安全的解决方案可能是添加一个变量来跟踪哪个线程在哪里启动。但是,我想知道是否可以检查 pthread_t 变量,类似于以下代码。
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);
其中 some_invalid_value 可以是 0,或依赖于实现的“PTHREAD_INVALID_ID”宏
PS: 我的假设是 pthread_t 类型是可比较和可分配的,假设基于
PPS: 我想这样做,因为我认为在无效线程 id 上调用 pthread_join 是未定义的行为。它不是。但是,加入先前加入的线程是未定义的行为。现在让我们假设上面的“函数”被重复调用。 无条件调用 pthread_join 并检查结果可能会导致在先前加入的线程上调用 pthread_join。
【问题讨论】:
-
您总是可以使用 pthread_self()... 一个您可能不会加入的线程 ;-)。可以使用
pthread_t invalid_thread = pthread_self()来提高可读性。