[pthread] pthread_join与pthread_detach

pthread_t    pthr;

pthread_create(&pthr, NULL, thread_handler, NULL);

...

void* thread_handler(void* arg)

{

    /* do something */

    pthread_join(pthr, NULL);

}


上面的代码不好使,pthread_join不能放在pthread调用的handler内,虽然不报错,但是thread无法正常回收,如果多次创建thread,内存会越来越大(另一种形式的内存泄露)。

正确的做法是在handler外面pthread_join:


pthread_t    pthr;

pthread_create(&pthr, NULL, thread_handler, NULL);

pthread_join(pthr, NULL);

...

void* thread_handler(void* arg)

{

    /* do something */

}


如果不用pthread_join,改用pthread_detach呢?那最方便,但要注意:pthread_detach最好是放在handler里面第一句。


void* thread_handler(void* arg)

{

    pthread_detach(pthr);

    /* do something */

}


如果pthread_create后紧跟pthread_detach,有可能会出错。


相关文章

分类

留言:

关于文章

This page contains a single entry by DongHao published on 01 27, 2010 5:21 PM.

[shell] grep里的星号(*)和双引号(“) was the previous entry in this blog.

[tcp] http_load报"Cannot assign requested address" is the next entry in this blog.

Find recent content on the main index or look in the 存档 to find all content.