【问题标题】:pthread_cancel() not working when passing in a type casted void pointer传入类型转换的 void 指针时 pthread_cancel() 不起作用
【发布时间】:2017-06-07 16:51:27
【问题描述】:

我正在处理一个项目,该项目要求我使用 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 吗?我很困惑……

【问题讨论】:

  • 你的逻辑真的没有任何意义。由于temp 是一个指向void 的指针,你将不得不使用它来指向pthread_t。但是你在哪里分配任何pthread_t 让它指向?

标签: c multithreading pthreads void-pointers


【解决方案1】:

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

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

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

我的建议是跳过ThreadHandle_t 类型,只需从createThread 函数返回一个pthread_t(不是指针),然后将其按原样传递给需要它的函数。

【讨论】:

  • 啊,当然!谢谢你。不幸的是,createThread 函数无法返回 pthread,因为我正在尝试使用这些相同的函数制作可以移植到另一个平台的东西。我认为最好的方法是将 ThreadHandle_t 类型定义为 pthread,而不是 void 指针。
【解决方案2】:

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

createThread 返回后,你的句柄指向空。

【讨论】:

    猜你喜欢
    • 2015-02-14
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2014-02-06
    • 2020-08-12
    相关资源
    最近更新 更多