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

代码示例


```c
#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);
}

猜你喜欢

转载自blog.csdn.net/u010835747/article/details/105110336
今日推荐