pthread_cancel() 在传入类型转换的 void 指针时不起作用

pthread_cancel() not working when passing in a type casted void pointer

我正在做一个项目,它要求我使用 void 指针存储对 pthread 的所有引用,并使用包装函数创建和取消这些线程。

因此我得到了以下结果:

typedef void * ThreadHandle_t;

void * endlessWhileLoop(void * p){
    while(1);
} 

int createThread(ThreadHandle_t * handle){
    pthread_t thread;
    int ret = pthread_create(&(thread), NULL, endlessWhileLoop, NULL);
    if (ret != 0) {
        return -1;
    }

    /* Configure the ThreadHandle to point to the task */
    if (handle != NULL) {   /* If handle was passed in */
        *handle = &thread;
    }
    //ret = pthread_cancel(*(pthread_t *)*handle); <--This works

    return ret;

}

int deleteThread(ThreadHandle_t handle){
    int ret = pthread_cancel(*(pthread_t *)handle);

    if(ret != 0){
        printf("Failed to delete task, return code: %d", ret);
        return -1;
    }

    return ret;
}

int main( void ){
    ThreadHandle_t temp = 0;
    createThread(&temp);
    deleteThread(temp);
}

但是,我从 deleteThread 中的 cancel_thread 调用中收到找不到线程的错误。

如果我将 pthread_cancel 调用转移到 createThread 函数中,它将起作用,并且线程被取消,即使在使用 ThreadHandle 时也是如此。

会不会是我没有通过引用正确地使用 ThreadHandle_t 传递 pthread_t?我很困惑...

这是一个大问题(来自您的 createThread 函数):

pthread_t thread;
...
*handle = &thread;

这里你让 *handle 指向 local 变量 thread。但是请记住,当函数 returns 时 thread 将超出范围,指针将不再有效。当您稍后尝试使用此无效指针时,这将导致 未定义的行为

我的建议是您跳过 ThreadHandle_t 类型,只需 return 来自 createThread 函数的 pthread_t (不是指针),并将其作为它是需要它的功能。

你的pthread是createThread中的局部变量。这是错误的。将其设为全局或在主函数中定义。

createThread returns 后,您的句柄未指向任何内容。