线程的创建与退出

来源:互联网 发布:淘宝退货卖家说损坏了 编辑:程序博客网 时间:2024/05/16 06:52

头文件   #include <pthread.h>

线程的创建   pthread_create()

线程的退出   pthread_exit()

等待线程的退出  pthread_join()

#include <stdio.h>#include <stdlib.h>#include <pthread.h>void thread(){        printf("This is child thread!\n");        return ;}int main(){        pthread_t id;          int ret;        ret = pthread_create(&id, NULL, (void *)thread, NULL); //创建线程(第一个参数是线程号;第二个参数为线程属性,一般置为NULL;
                                                        //第三个参数为线程要调用的函数的首地址;第四个参数为传递给线程函数的参数)        if(ret != 0)        {                perror("pthread_create.");                exit(1);        }        printf("This is main thread!\n");        pthread_join(id, NULL);   //等待线程结束        printf("Child thread return.\n");        return 0;}
执行结果:

This is main thread!
This is child thread!
Child thread return.


#include <stdio.h>#include <stdlib.h>#include <errno.h>#include <pthread.h>void* thread(int num){        printf("This is chlid thread!\n");        num *= 2;        //return (void *)num;        pthread_exit((void *)10);}int main(){        pthread_t id;        int ret;        void *result;        ret = pthread_create(&id, NULL, (void *)thread, (void *)5);        if(ret != 0)        {                perror("pthread_create");                exit(1);        }        printf("This is main thread!\n");        pthread_join(id, &result);   //第二个参数为void ** 型,用来取得线程退出信息。        printf("Child thread return %d.\n",(int)result);        return 0;}

执行结果:

This is main thread!
This is chlid thread!
Child thread return 10.


关于return 与 pthread_exit(void *)的区别:

对于线程函数来说,调用return和pthread_exit()都将使该线程返回。但return所做的是函数返回(在线程结束的时候会自动调用pthread_exit()来释放线程所占用的资源,包括主线程),而phtread_exit()则显式的释放空间并设置了返回值。pthread_exit()属于线程退出函数,但renturn不是。

两者都会将退出的值放到pthread_join(id, void **)中的第二个参数所指向的地址里,主线程也就获得了子线程返回的信息。



关于线程的操作还有一些函数:

int pthread_detach(pthread_t tid)   //使该线程从进程中分离(分离后线程会自动释放资源)

int pthread_cancel(pthread_t tid)   //用来取消一个线程


void pthread_cleanup_push(void (*rtn)(void *), void *arg);   //用来设置线程的清理程序

void pthread_cleanup_pop(int execute);

(以上两个函数必须成对出现)

更多信息参考:

http://www.ibm.com/developerworks/cn/linux/thread/posix_threadapi/part4/

http://blog.chinaunix.net/uid-23193900-id-3193923.html