【发布时间】: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