线程创建--pthread_create
#include <pthread.h>
int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void *(*routine)(void*),void *arg);
成功时返回0,失败返回错误码
thread线程对象
attr线程属性,NULL代表默认属性
routine线程执行的函数
arg传递给routine的参数,不需要传参就NULL
线程回收--pthread_join
linux线程执行和windows不同,pthread有两种状态joinable状态和unjoinable状态,如果线程是joinable状态,当线程函数自己返回退出时或pthread_exit时都不会释放线程所占用堆栈和线程描述符(总计8K多)。只有当你调用了pthread_join之后这些资源才会被释放,释放动作是由主线程完成的。若是unjoinable状态的线程,这些资源在线程函数退出时或pthread_exit时自动会被释放。
unjoinable属性可以在pthread_create时指定,或在线程创建后在线程中pthread_detach自己, 如:pthread_detach(pthread_self()),将状态改为unjoinable状态,确保资源的释放。或者将线程置为 joinable,然后适时调用pthread_join.
其实简单的说就是在线程函数头加上 pthread_detach(pthread_self())的话,线程状态改变,在函数尾部直接 pthread_exit线程就会自动退出。省去了给线程擦屁股的麻烦。
pthread_join()即是子线程合入主线程,主线程阻塞等待子线程结束,然后回收子线程资源。
线程分离--pthread_detach()
pthread_detach()即主线程与子线程分离,子线程结束后,资源自动回收。即不需要主线程回收资源。
该函数为pthread_join()函数的替代函数,可回收创建时detachstate属性设置为PTHREAD_CREATE_JOINABLE的线程的存储空间。该函数不会阻塞父线程。pthread_join()函数用于只是应用程序在线程tid终止时回收其存储空间。如果tid尚未终止,pthread_detach()不会终止该线程。当然pthread_detach(pthread_self())也是可以的。