线程等待

来源:互联网 发布:电机pid控制算法 编辑:程序博客网 时间:2024/06/10 00:12
 

/*线程等待*/
/*thread_join.c*/
/*代码分析:进程在创建线程后各自独立运行,pthread_join系统调用会使进程阻塞等待线程的退出*/
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>

void *thread(void *str)
{
 int i;
 for(i=0;i<3;i++)
 {
  sleep(2);
  printf("this in the thread:%d\n",i);
 }
 return NULL;
}
int main()
{
 pthread_t pth;
 int i;
 /*创建线程并执行线程执行函数*/
 int ret=pthread_create(&pth,NULL,thread,NULL);
 printf("The main process will be to run,but will be blocked soon\n");
 /*阻塞等待进程以等待线程的退出*/
 pthread_join(pth,NULL);
 printf("thread was exit\n");
 for(i=0;i<3;i++)
 {
  sleep(1);
  printf("this in the main:%d\n",i);
 }
 return 0;
}