1、线程的概念ide
线程是进程内部的一个基本执行流,是系统调度的一个实体。进程具备独占性,线程具备共享性。各线程共享进程的文件描述符、信号处理的方式、当前的工做目录、用户id(uid)和组id(gid)。可是有些资源线程是私有的,好比线程id、栈空间、上下文(包括各类寄存器的值。程序计数器和栈指针)、占空间、信号屏蔽字、调度优先级。就比如进程若是是一个家庭的话,线程就是这个家庭的成员,每一个家庭的成员都有一个公共的空间(餐厅,客厅)。固然每一个家庭成员也有本身的私人空间了。
函数
2、线程的控制ui
建立线程和终止this
用函数pthread_create()建立,成功返回0,失败返归错误号。调用 pthread_create()建立新的线程后。当前线程从pthread_create()返回继续往下执行。新的线程所执行的代码由函数指针start_routine决定。函数start_routine函数接收一个参数,是经过pthread_create()的arg传给它的。类型为void*,start_toutine的返回值类型也是void*,start_toutine返回后,这个线程就退出了,其余线程能够调用pthread_join()获得start_toutine的返回值。start_toutine函数能够经过①return(void*)、②pthread_exit(void*)、③pthread_cancel(pthread_self())三种终止。
spa
1 #include<stdio.h> 2 #include<pthread.h> 3 void * thread_run(void* arg) 4 { 5 int count=5; 6 while(1) 7 { 8 printf("this is a thread,thread id is\n"pthread_self()); 9 sleep(1); 10 } 11 //return (void*)1; 12 //pthread_exit((void*)2); 13 // pthread_cancel(pthread_self()); 14 } 15 int main() 16 { 17 pthread_t id; 18 int ret=pthread_create(&id,NULL,thread_run,NULL); 19 int count=10; 20 while(count-->0) 21 { 22 printf("this is a main thread,thread id is %u\n",pthread_self()); 23 sleep(1); 24 } 25 void * ted=0; 26 pthread_cancel(id); 27 pthread_join(id,&ted); 28 printf("return success %d\n",(int)ted); 29 }
一、若是经过return返回。pthread_join接收的值是线程的返回值
指针
二、若是线程被别的线程调用pthread_cancel异常终止掉。则返回错误码
blog
三、若是是调用pthread_exit终止的。pthread_join存放的是传给pthread_exit的参数。
进程
四、两个线程的线程号是不同的
内存
3、线程分离
线程在任一个时间点上。是可结合的(joinable)或者是可分离的(detached)。可结合的线程可被其余的线程回收资源和杀死。在被其余线程回收以前,它的存储器资源是不释放的。而可分离的线程是不能被其余回收或杀死的,它的存储器资源在它终止时由系统自动释放。默认状况下。线程被建立成可结合的。为了不内存泄漏,每一个可结合的线程都应该要么被显示的回收,即调用pthread_join;要么经过pthread_detach函数分离。
若是若是一个可结合线程结束运行但没有被pthread_join,则它的状态相似于进程中的僵尸进程,即还有一部分资源没有被回收,因此建立线程者应该调用pthread_join来等待线程运行结束,并可获得线程的退出代码,回收其资源。调用pthread_join后,若是该线程没有运行结束,调用者会被阻塞。这是能够在子线程中加入代码pthread_detach(pthread_self())或者父线程调用pthread_detach(thread_id)非阻塞,可当即返回。这将该子线程的状态设置为分离的(detached),如此一来,该线程运行结束后会自动释放全部资源。
1 #include<stdio.h> 2 #include<pthread.h> 3 void* thread_run(void* arg) 4 { 5 pthread_detach(pthread_self()); //分离线程 6 printf("this is a thrad \n"); 7 return (void*)1; 8 } 9 int main() 10 { 11 pthread_t id; 12 int ret= pthread_create(&id,NULL,thread_run,NULL); 13 printf("this is a main thread\n"); 14 sleep(1); 15 16 int res=pthread_join(id,NULL); 17 if(res==0) 18 { 19 printf("pthrad wait succced\n"); 20 return 0; 21 } 22 else 23 { 24 printf("pthread wait faile\n"); 25 return 1; 26 } 27 return 0; 28 }
若是把子线程中的pthread_detach(pthread_self())注释掉,则结果以下,这是由于把子线程中分离去掉后,其余线程就能够对子线程进程join和杀死,而后释放掉存储器资源。而上面是由于在子进程中已经分离的,因此其余线程不能在对其访问了,join返回fail
总结:
线程的控制从建立线程-->子线程的三种终止方式-->其余线程join线程。终止的方式不一样,join的返回值就不一样。线程的分离,若是子线程中加入pthread_detach()就把子线程设置成了可分离的线程,线程退出后会自动释放存储器资源,不会形成内存泄漏。若是不设置的话,就要用join显示接收,而后释放资源,也不会形成内存泄漏。