pthread_create()

来源:互联网 发布:linux 驱动 培训 编辑:程序博客网 时间:2024/04/20 05:19

http://blog.csdn.net/youbang321/article/details/7815707

pthread_create函数

    原型:int  pthread_create((pthread_t  *thread,  pthread_attr_t  *attr,  void  *(*start_routine)(void  *),  void  *arg)

    用法:#include  <pthread.h>

    功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。

    说明:thread:线程标识符;

              attr:线程属性设置;

              start_routine:线程函数的起始地址;

              arg:传递给start_routine的参数;

              返回值:成功,返回0;出错,返回-1。

    举例:

  1. /*thread.c*/  
  2. #include <stdio.h>  
  3. #include <pthread.h>  
  4.   
  5. /*线程一*/  
  6. void thread_1(void)  
  7. {  
  8.     int i=0;  
  9.     for(i=0;i<=6;i++)  
  10.     {  
  11.         printf("This is a pthread_1.\n");  
  12.         if(i==2)  
  13.             pthread_exit(0);  
  14.         sleep(1);  
  15.     }  
  16. }  
  17.   
  18. /*线程二*/  
  19. void thread_2(void)  
  20. {  
  21.     int i;  
  22.     for(i=0;i<3;i++)  
  23.         printf("This is a pthread_2.\n");  
  24.     pthread_exit(0);  
  25. }  
  26.   
  27. int main(void)  
  28. {  
  29.     pthread_t id_1,id_2;  
  30.     int i,ret;  
  31. /*创建线程一*/  
  32.     ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);  
  33.     if(ret!=0)  
  34.     {  
  35.         printf("Create pthread error!\n");  
  36.     return -1;  
  37.     }  
  38. /*创建线程二*/  
  39.      ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);  
  40.     if(ret!=0)  
  41.     {  
  42.         printf("Create pthread error!\n");  
  43.     return -1;  
  44.     }  
  45. /*等待线程结束*/  
  46.     pthread_join(id_1,NULL);  
  47.     pthread_join(id_2,NULL);  
  48.     return 0;  
  49. }  

    以下是程序运行结果:

     备注:pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以线程函数在编译时,需要连接库函数,如上图    gcc pthread_create.c -o pthread_create -lpthread


0 0
原创粉丝点击