我想为给定的线程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);
Run Code Online (Sandbox Code Playgroud)
其中some_invalid_value可以是0,或者是依赖于实现的'PTHREAD_INVALID_ID'宏
PS:我的假设是pthread_t类型具有可比性和可分配性,基于的假设
PPS:我想这样做,因为我认为在无效的线程id上调用pthread_join是未定义的行为.它不是.但是,加入以前加入的线程是未定义的行为.现在让我们假设重复调用上面的"函数".无条件地调用pthread_join并检查结果可能会导致在先前连接的线程上调用pthread_join.
qbe*_*220 17
你的假设开始是不正确的.pthread_t对象是不透明的.您无法直接在C中比较pthread_t类型.您应该使用pthread_equal.
另一个考虑因素是如果pthread_create失败,pthread_t的内容将是未定义的.它可能不再设置为您的无效值.
我的首选是保持pthread_create调用的返回值(以及线程ID),并使用它来确定每个线程是否正确启动.
Mat*_*Mat 12
正如Tony所建议的那样,你可以pthread_self()在这种情况下使用.
但是不要thread_t使用==或比较s !=.使用pthread_equal.
从pthread_self手册页:
因此,使用C相等运算符(==)无法可移植地比较pthread_t类型的变量; 请改用pthread_equal(3).