【发布时间】:2018-02-01 09:48:46
【问题描述】:
我有一些动态分配,我想确保在线程退出/终止时释放它们。
请考虑以下场景:
static void thread_cleanup_handler(void* arg)
{
free(arg);
}
static void* threadFunction(void* arg)
{
pthread_cleanup_push(thread_cleanup_handler, arg);
//do some work with arg...
pthread_cleanup_pop(1);
return NULL;
}
something* data = (something*)malloc(sizeof(something));
pthread_create(&id, &attr, threadFunction, (void*)data); //thread is created detached
问题是,如果创建的线程在它实际开始运行之前被取消(使用pthread_cancel)(它只是被调度并且尚未被执行),清理处理程序会被调用还是被调用?这是潜在的内存泄漏?
请注意线程是用 PTHREAD_CREATE_DETACHED 创建的。
【问题讨论】:
标签: c linux multithreading pthreads