2011-05-15 142 views
0

我想获得一个函数来启动另一个线程,然后返回,线程仍在运行。看起来pthread_detach()会照顾内存和不适合我的东西,虽然我不完全确定。这是函数的代码:正确使用pthread_detach

void function() { 
    pthread_mutex_lock(&state.continueLoopingMutex); 
    if(state.continueLooping == true) { 
     pthread_mutex_unlock(&state.continueLoopingMutex); 
     return; 
    } 
    state.continueLooping = true; 
    pthread_mutex_unlock(&state.continueLoopingMutex); 
    pthread_t thread; 
    pthread_create(&thread, NULL, runLoop, NULL); 
    pthread_detach(thread); 
} 

(当continueLooping设置为false,一旦循环结束,它只是返回,而不做其他任何事情的循环将停止)。

这个结构有什么问题会导致内存泄漏等,我应该关心吗?

谢谢

回答

3

我没有看到任何错误。
是的pthread_detach将小心释放线程的资源。

2

如果你只想让线程同时运行,不管你是否分离线程都没有区别。但从分离的线程收集资源(如返回值)会更难或更不习惯。是的,这段代码不会泄露任何内存泄漏。