linux线程编程示例

Linux线程编程

线程编程和rtos实时任务创建差不多,比进程更节省资源

线程头文件
#include<pthread.h>

函数原型
1.创建线程
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
参数:thread:线程id(输出型参数)
attr:线程属性,一般设置为NULL
tart_routine:线程函数指针
arg:一般设置为NULL
返回值:成功 0,错误 故障号

2.线程等待
int pthread_join(pthread_t thread, void **retval);
参数:thread:线程号tid
retval:要等待线程的退出码
返回:成功0,失败 故障号

编译需要添加-lpthread
例如gcc main.c -o main -lpthread

代码示例

#include<pthread.h>
#include<stdlib.h>

static void *my_pthread1(void *arg)
{
	printf("pthread1 start\n"); 
	sleep(1);

	while(1)
	{
		printf("pthread1 run\n"); 
	}
}
static void *my_pthread2(void *arg)
{
	printf("pthread1 start\n"); 

	while(1)
	{
		printf("pthread2 run\n"); 
	}
}
Int main(void)
{
	pthread_t tidp,tidp1;
	static int num[10] = {0};
	static int num1[10] = {0};

	printf("create pthread test!\n");
	if ((pthread_create(&tidp, NULL, my_pthread1, (void*)num)) == -1)
	{
		printf("create pthreaderror!\n");
	}
	
	if ((pthread_create(&tidp1, NULL, my_pthread2, (void*)num1)) == -1)
	{
		printf("create pthreaderror!\n");
	}
	pthread_join(tidp,NULL);//join run team
	pthread_join(tidp1,NULL);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值