foggia2004

线程的返回值与资源管理

线程的返回值
当线程退出时,线程可以选择向主线程返回一个值,返回方式一共有4种
1\如果要返回int类型,可以使用pthread_exit((int)* return_value);
2\使用全局变量返回(这个最简单)
3\使用malloc所分配的空间
4\直接返回字符串,如pthread_exit("return value");

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <pthread.h>

void *thread1(void)
{
        printf("this is thread 1, return value : hello world, I love you!\n");
        pthread_exit("hello world, I love you!");
}

int main(int argc, char argv[])
{
        int result = 0;
        void *return_value;
        pthread_t th1;
        result = pthread_create(&th1, NULL, thread1, NULL);
        if(result != 0)
        {
                printf("create pthread failed, app exit!\n");
                exit(-1);
        }
        printf("create pthread succeed!\n");
        pthread_join(th1,&return_value); /* 等待线程返回后,该函数会清理掉该线程的资源 */
        printf("return value : %s\n", (char *)return_value);
        return 0;
}

 

手动连接线程以清理资源, pthread_join:

当线程组类的其他线程调用了pthread_join连接退出线程的时候,内部会调用__free_tcb函数,该函数会负责释放退出线程的资源.但即使是调用了pthread_join,也并没有立即调用munmap来释放退出线程的栈,他们是被后建的线程复用了.因为NPTL认为进程有可能会再次创建线程,频繁的调用munmap和mmap会影响性能.所以,NTPL将该栈缓存起来,放到一个链表中,如果有新的创建线程的请求,NPTL会首先在栈缓存链表中寻找空间合适的栈,有的话,就直接分配出去.

 

让系统自动清理退出线程的资源, pthread_detach:

该方法会将线程设置为已分离状态,那么当该线程退出时,系统会自动清理掉它的资源.

posted on 2017-01-10 11:33  foggia2004  阅读(288)  评论(0)    收藏  举报

导航