多线程编程——线程连接join

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
/* 线程控制块 */
static pthread_t tid1;
static pthread_t tid2;
/* 函数返回值检查 */
static void check_result(char* str,int result)
{
	if (0 == result)
	{
		printf("%s successfully!\n",str);
	}
	else
	{
		printf("%s failed! error code is %d\n",str,result);
	}
}
/* 线程1入口函数 */
static void* thread1_entry(void* parameter)
{
	int i;
	for (i = 0;i < 3;i++) /* 循环打印3次信息 */
	{
		printf("thread1 run count: %d\n",i);
		sleep(2); /* 休眠2秒 */
	}
	printf("thread1 exited!\n");
	return NULL;
}
/* 线程2入口函数*/
static void* thread2_entry(void* parameter)
{
	int count = 0;
	void* thread1_return_value;
	/* 阻塞等待线程1运行结束 */
	pthread_join(tid1, NULL);
	/* 线程2打印信息开始输出 */
	while(1)
	{
		/* 打印线程计数值输出 */
		printf("thread2 run count: %d\n",count ++);
		sleep(2); /* 休眠2秒 */
	}
	return NULL;
}
/* 用户应用入口 */
int application_init()
{
	int result;
	/* 创建线程1,属性为默认值,分离状态为默认值joinable,
	* 入口函数是thread1_entry,入口函数参数为NULL */
	result = pthread_create(&tid1,NULL,thread1_entry,NULL);
	check_result("thread1 created",result);
	/* 创建线程2,属性为默认值,分离状态为默认值joinable,
	* 入口函数是thread2_entry,入口函数参数为NULL */
	result = pthread_create(&tid2,NULL,thread2_entry,NULL);
	check_result("thread2 created",result);
	return 0;
}
int main()
{
	int i ;
	application_init();
	i=10;
	do{
		sleep(1);
	}while(i--);
}

运行结果:

-bash-3.2$ gcc join.c -pthread -o app
-bash-3.2$ ./app
thread1 created successfully!
thread2 created successfully!
thread1 run count: 0
thread1 run count: 1
thread1 run count: 2
thread1 exited!
thread2 run count: 0
thread2 run count: 1
thread2 run count: 2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值