Linux线程学习总结

来源:互联网 发布:程序员到架构师 编辑:程序博客网 时间:2024/05/20 13:13
线程
线程的概念:线程被称为轻量级进程(LWP),是程序执行流的最小单元,一个标准的线程由线程ID,当前指令指针,寄存器集合和指令指针组成。线程是进程中的一个实体,是被系统调度和分配的基本单位,线程自己除了拥有运行的必要资源外不拥有系统资源,但是它可以与同属一个进程的其他线程共享进程的所有资源。线程有就、阻塞、运行三种状态。
线程与进程的区别:
1.进程至少有一个线程;它们共享进程的地址空间,而进程有自己的地址空间。
2.进程是资源分配和拥有的单位,同一个进程内的线程共享进程资源。
3.线程是处理器调度的基本单位,但是进程不是。
4.二者均可并发执行





线程的分离和结合:

分离与结合都是线程的属性,默认创建的线程是可结合的,一个可结合的线程能够被其他线程回收资源和杀死,在被其他线程回收之前,他的存储器是不释放的,所以主线程必须等待子线程回收其状态。


若是一个线程变为可分离的,这个线程是不能被其他线程回收和杀死,他的存储器资源在他被终止时由系统自动释放。所以他此时与主线程关系不大,但在当前进程退出时,该分离线程也会退出,虽然他已经分离,但他的资源依然是当前进程的,进程退出资源回收,该线程也必定随之退出。

8 #include<stdio.h>  9 #include<stdio.h> 10 #include<stdlib.h> 11 #include<pthread.h> 12  13 pthread_t tid; 14  15 void* thread_run(void *_val) 16 { 17     printf("%s :pid is : %d, tid is :%u \n",(char*)_val,(int)getpid(),(unsig    ned long long )pthread_self()); 18      return NULL; 19              20 } 21  22 void *pthread1(void *_val)       23 { 24     printf("thread 1 returning ...\n'"); 25     return (void*)1; 26 } 27  28  29 void* pthread2(void *_val) 30 { 31     printf("thread 2 exit! \n"); 32     pthread_exit((void*)2); 33 } 34  35  36 void* pthread3(void *_val) 37 { 38     while(1) 39     { 40         printf("pthread 3 is running,wait for be cancal\n"); 41         sleep(1); 42     } 43     return NULL; 45}  46 int main() 47 { 48      int ex=pthread_create(&tid,NULL,thread_run,"other thread run"); 49  50      if(ex!=0){ 51      printf("Create thread error ! info is :%s\n",strerror(ex)); 52      exit(ex); 53      } 54      printf("main thread run :pid is %d,tid is:%u\n",(int)getpid(),(unsigned     long long)pthread_self()); 55     sleep(1); 56  57  58  59     pthread_t tid; 60     void *tret; 61     pthread_create(&tid,NULL,pthread1,NULL); 62     pthread_join(tid,&tret); 63     printf("thread return,id is:%u,return code is :%d\n",(unsigned long)tid,    (int)tret); 64  65  66  67     pthread_create(&tid,NULL,pthread2,NULL); 68     pthread_join(tid,&tret); 69     printf("thread return,id is:%u,return code is :%d\n",(unsigned long)tid,    (int)tret); 70  71  72  73  74     pthread_create(&tid,NULL,pthread3,NULL); 75     sleep(3); 76     pthread_cancel(tid); 77     pthread_join(tid,&tret); 78     printf("thread return,id is:%u,return code is :%d\n",(unsigned long)tid,    (int)tret);          return 0;}


原创粉丝点击