Chinaunix首页 | 论坛 | 博客
  • 博客访问: 194660
  • 博文数量: 81
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 540
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-04 12:48
文章分类
文章存档

2015年(23)

2014年(58)

我的朋友

分类: C/C++

2014-08-28 15:30:56

pthread_create函数

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

    用法:#include 

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

    说明:thread:线程标识符;

              attr:线程属性设置;

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

              arg:传递给start_routine的参数;

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

    举例:

  1. /*thread.c*/  
  2. #include   
  3. #include   
  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

阅读(809) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~