初步了解多线程库pthread

  1. 创建进程–pthread_create(参数1,参数2,参数3,参数4),它是类Unix操作系统(Unix、Linux、Mac OS X等)的创建线程的函数。
    参数1:线程标识符,即线程ID,标识所创建进程;
    参数2:设置线程属性,通常为NULL;
    参数3:所创建线程的运行函数(起始地址);
    参数4:运行函数的参数。

  2. 等待子进程–pthread_join(参数1,参数2),即pthread_join之后的代码要在子进程完成之后才能继续执行。
    参数1:线程标识符,即线程ID,标识唯一线程;
    参数2: 用户定义的指针,用来存储被等待线程的返回值。

  3. 代码

#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;
}
  1. 结果展示
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值