-
创建进程–pthread_create(参数1,参数2,参数3,参数4),它是类Unix操作系统(Unix、Linux、Mac OS X等)的创建线程的函数。
参数1:线程标识符,即线程ID,标识所创建进程;
参数2:设置线程属性,通常为NULL;
参数3:所创建线程的运行函数(起始地址);
参数4:运行函数的参数。 -
等待子进程–pthread_join(参数1,参数2),即pthread_join之后的代码要在子进程完成之后才能继续执行。
参数1:线程标识符,即线程ID,标识唯一线程;
参数2: 用户定义的指针,用来存储被等待线程的返回值。 -
代码
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//所创建线程的运行函数
void *test(void *ptr)
{
int i;
for(i=0;i<6;i++)
{
printf("child pthread running ,count: %d\n",i);
sleep(1);
}
}
int main (int argc,char* argv)
{
pthread_t pId;
int i,ret;
//创建子线程,线程id为pId
ret = pthread_create(&pId,NULL,test,NULL);
if(ret != 0)
{
printf("create pthread error!\n");
exit(1);
}
//3个父线程,5个子线程
for(i=0;i < 3;i++)
{
printf("father thread running ,count : %d\n",i);
sleep(1);
}
printf("father thread finishhed but will exit when child pthread is over\n");
//等待线程pId的完成
pthread_join(pId,NULL);
printf("father thread exit\n");
return 0;
}
- 结果展示