日期:2014-05-16  浏览次数:20773 次

关于pthread_join()例子,请教高手。
《unix环境高级编程》(中文版)p292的一个例子:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>

void *thr_fn1(void *arg)
{
  printf("thread 1 returning\n");
  return((void*)1);
}
void *thr_fn2(void *arg)
{
  printf("thread 2 exiting\n");
  pthread_exit((void*)2);
}
int main()
{
  int err;
  pthread_t tid1,tid2;
  void *tret;
  err = pthread_create(&tid1,NULL,thr_fn1,NULL);
  if (err != 0)

  printf("can't create thread 1:%s\n",strerror(err));
  err = pthread_create(&tid2,NULL,thr_fn2,NULL);
  if (err != 0)
  printf("can't create thread 2:%s\n",strerror(err));
  err = pthread_join(tid1,&tret);
  if (err != 0)
  printf("can't join with thread 1:%s\n",strerror(err));
  printf("thread 1 exit code %d\n",(int)tret);
  err = pthread_join(tid2,&tret);
  if (err != 0)
  printf("can't join with thread 2:%s\n",strerror(err));
  printf("thread 2 exit code %d\n",(int)tret);
  exit(0);
}
书上答案是:
thread 1 returning
thread 2 exiting
thread 1 exit code 1
thread 2 exit code 2
为什么我运行的结果有两种:
结果1
thread 1 returning
thread 2 exiting
thread 1 exit code 1
thread 2 exit code 2
结果2
thread 1 returning
thread 1 exit code 1
thread 2 exiting
thread 2 exit code 2
请问:结果1我始终想不明白,结果1的线程执行顺序是什么(麻烦详细点)?
结果2是我自己的理论分析结果(程序运行后也出现了这种情况),如果此种情况是错的,请问错在哪里?没错的话为什么会出现两种情况?先谢谢各位了。

------解决方案--------------------
这个是没有严格顺序的吧
看主线程与子线程,谁执行的快
------解决方案--------------------
首先把判错语句去掉 (干扰)
C/C++ code

void *thr_fn1(void *arg)
{
  printf("thread 1 returning\n");
  return((void*)1);
}
void *thr_fn2(void *arg)
{
  printf("thread 2 exiting\n");
  pthread_exit((void*)2);
}
int main()
{
  int err;
  pthread_t tid1,tid2;
  void *tret;

  err = pthread_create(&tid1,NULL,thr_fn1,NULL);

  err = pthread_create(&tid2,NULL,thr_fn2,NULL);

  err = pthread_join(tid1,&tret);

  printf("thread 1 exit code %d\n",(int)tret);
  err = pthread_join(tid2,&tret);

  printf("thread 2 exit code %d\n",(int)tret);
  exit(0);
}

------解决方案--------------------
这段代码涉及到了三个线程,它们没有确定的执行顺序,所以程序运行的u时候,结果也不会只有一个。
结果1的执行顺序是:
线程1 ---> 线程2 ----> 主线程

man上有这样的说明:
Unless real-time scheduling policies are being employed, after a call to pthread_create(), it is indeterminate which thread—the caller or the new thread—will next execute.