Chinaunix首页 | 论坛 | 博客
  • 博客访问: 536076
  • 博文数量: 67
  • 博客积分: 1625
  • 博客等级: 上尉
  • 技术积分: 1053
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-04 14:40
文章分类

全部博文(67)

文章存档

2012年(67)

分类: LINUX

2012-04-19 17:59:30

作者:kangear

邮箱:

 

多线程,国嵌的pthread_create.c中两个创建线程,两个函数都只分析一个:

 

thread_create.c

 


点击(此处)折叠或打开

  1. #include <stdio.h> //printf()
  2. #include <pthread.h> //pthread_create() pthread_join()

  3. void *myThread1(void) //返回指针值的函数 下详
  4. {
  5.     int i; //函数是一个循环,没什么可说的
  6.     for (i=0; i<2; i++)
  7.     {
  8.         printf("This is the 1st pthread,created by zieckey.\n");
  9.         sleep(1);//Let this thread to sleep 1 second,and then continue to run
  10.     }
  11. }

  12. void *myThread2(void)
  13. {
  14.     int i;
  15.     for (i=0; i<2; i++)
  16.     {
  17.         printf("This is the 2st pthread,created by zieckey.\n");
  18.         sleep(1);
  19.     }
  20. }

  21. int main() //主函数
  22. {
  23.     int i=0, ret=0; //初始化两个变量
  24.     pthread_t id1,id2; // pthread_t:《UNIX书》书上线程标识符 P288
  25.     
  26.     /*创建线程1(多线程第一步:创建线程(线程处于就绪态))*/
  27.     ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
  28. if (ret) //ret=0表示创建成功,否侧表示出错
  29.                          //if(ret) 等同于 if(ret !=0 ) 更容易理解
  30.     { //如果出错就打印错误信息
  31.         printf("Create pthread error!\n");
  32.         return 1;
  33.     }
  34.     
  35.     /*创建线程2*/
  36.     ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
  37.     if (ret)
  38.     {
  39.         printf("Create pthread error!\n");
  40.         return 1;
  41.     }
  42.     
  43. pthread_join(id1, NULL); //下详细解释
  44. pthread_join(id2, NULL);
  45.  return 0;
  46. }

pthread_join():如果最后没有pthread_join()那么线程就不会执行(如果主程序加上sleep()也可以执行)

1,  只要有其中一个就可以让 id1 id2都执行

2,  函数中sleep()像是乒乓球拍,在主程序中遇到pthread_join()就进入了乒乓时间,是 id1 id2运行顺序并不清楚,但是都是 id2 id1 id2 id1或者是反序运行,因为遇到sleep()就跳。

3,  id1 id2都运行之后就会退出线程,而主程序则会继续向下运行。

 

返回指针的函数:(谭老师这有详细解释)

 

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