Linux多线程

来源:互联网 发布:软件产品认证 编辑:程序博客网 时间:2024/06/06 18:21

一、线程的特点

1. 线程是进程的一个执行流,是CPU调度和分配的基本单位。线程是程序运行的最小单位。

2. 线程不会影响到其它线程的运行。比如一个线程崩溃,其它线程正常运行。

3. 同一进程内的线程共享进程的地址空间。


二、一个线程的组成

1. 一个指向当前被执行指令的指令指针

2. 一个栈空间

3. 一个寄存器值的集合

4. 一个私有的数据区


三、使用线程的优点

1. 同一进程下的多线程共享地址空间,减少的资源的浪费。

2. 线程间方便的通信机制。因为线程共享数据空间,所以通信十分方便。

3. 操作系统会保证当线程数不大于CPU数目时,不同的线程运行于不同的CPU上。

4. 改善程序结构。可以任务拆分成多个小任务,方便管理。


四、POSIX线程接口函数

1.pthread_create

函数作用: 创建线程

函数原型:int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg);

函数参数:thread  --线程标识符。

                  attr  --线程的属性,一般为NULL。

                  start_routine  --线程的执行函数,没有为NULL。

                  arg  --传入到线程执行函数的参数。

头文件:#include <pthread.h>

返回值:成功返回0,出错为非0。

2.  pthread_exit

函数作用:线程的退出

函数原型:void pthread_exit(void *value_ptr);

函数参数:value_ptr  --线程结束的返回值。

头文件:#include <pthread.h>

注意:线程的退出只能由自己调用。

3. pthread_join

函数作用:等待线程 

函数原型:int pthread_join(pthread_t thread, void **value_ptr);

函数参数:thread  --线程的标识符。

               value_ptr  --不为NULL,储存线程结束的返回值。

头文件:#include <pthread.h>

返回值:成功返回0,出错返回非0。

五、参考代码

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4. voidvoid *myThread1(void)  
  5. {  
  6.     int i;  
  7.     for (i=0; i<3; i++)  
  8.     {  
  9.         printf("This is the 1st pthread,created by zieckey.\n");  
  10.         sleep(1);//Let this thread to sleep 1 second,and then continue to run  
  11.     }  
  12. }  
  13.   
  14. voidvoid *myThread2(void)  
  15. {  
  16.     int i;  
  17.     for (i=0; i<3; i++)  
  18.     {  
  19.         printf("This is the 2st pthread,created by zieckey.\n");  
  20.         sleep(1);  
  21.     }  
  22. }  
  23.   
  24. int main()  
  25. {  
  26.     int i=0, ret=0;  
  27.     pthread_t id1,id2;  
  28.   
  29.     /*创建线程1*/  
  30.     ret = pthread_create(&id1NULL, (void*)myThread1NULL);  
  31.     if (ret)  
  32.     {  
  33.         printf("Create pthread error!\n");  
  34.         return 1;  
  35.     }  
  36.   
  37.     /*创建线程2*/  
  38.     ret = pthread_create(&id2NULL, (void*)myThread2NULL);  
  39.     if (ret)  
  40.     {  
  41.         printf("Create pthread error!\n");  
  42.         return 1;  
  43.     }  
  44.   
  45.     pthread_join(id1NULL);  
  46.     pthread_join(id2NULL);  
  47.   
  48.     return 0;  
  49. }  
0 0