多线程编程:分离线程与分离已创建线程

分离已创建线程:

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
#include <string.h>
#include <unistd.h>
void * tfn1(void * arg){ 
    printf("the sub thread sleeping for 5 seconds\n");
    sleep(5);
    printf("the thread done\n");
    return NULL; 
}
int main(void){ 
    int iRet; 
    pthread_t tid;
    iRet = pthread_create(&tid, NULL, tfn1, NULL); 
    if(iRet){ 
        printf("can't create thread %s\n", strerror(iRet)); 
        return iRet;
    } 
    iRet = pthread_detach(tid);
    if(iRet){ 
        printf("can't detach thread  %s\n", strerror(iRet)); 
        return iRet;
    }
    iRet = pthread_join(tid, NULL);
    if(iRet){
        printf("thread has been detached\n");
    }
    printf("the main thread sleeping for 8 seconds\n");
    sleep(8);
    printf("the main thread done.\n");      
    return 0; 
}

分离线程:

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
#include <string.h>
void * tfn1(void * arg){ 
    printf("the thread\n");  
    return NULL; 
}  
int main(void){ 
    int iRet; 
    pthread_t tid; 
    pthread_attr_t attr; 
     iRet = pthread_attr_init(&attr); 
    if(iRet){ 
        printf("can't init attr %s/n", strerror(iRet)); 
        return iRet;
    } 
    iRet = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    if(iRet){ 
        printf("can't set attr %s\n", strerror(iRet)); 
        return iRet;
    } 
    iRet = pthread_create(&tid, &attr, tfn1, NULL);
    if(iRet){ 
        printf("can't create thread %s\n", strerror(iRet)); 
        return iRet; 
    } 
    iRet = pthread_join(tid, NULL);
    if(iRet){ 
        printf("thread has been detached\n"); 
        return iRet;
    }
    return 0; 
}

CMakeLists.txt  参考http://blog.csdn.net/dengshuai_super/article/details/52038970

posted on 2017-03-14 16:14  杜聪  阅读(137)  评论(0)    收藏  举报

导航