开发者

Proper usage of pthread_detach

I'm trying to get a function to start up another thread, and then return, with the thread still running. It seems like pthread_detach() would take care of the memory and whatnot for me, although I'm not entirely sure. This is the code for the function:

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);
}开发者_如何学Python

(The loop will stop when continueLooping is set to false, once the loop finishes it just returns without doing anything else).

Is there anything wrong with this structure that would cause a memory leak, etc., that I should care about?

Thank you


I don't see anything wrong.
Yes the pthread_detach will take care to release the resources of the thread.


If you only want the threads continue to run simultaneously, it won't make a difference whether you detach the thread or not. But it will be harder or less idiomatic to collect resource (like a return value) from a detached thread. And yes, this piece of code does not expose any memory leaks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜