linux thread programming example

Linux thread programming

Thread programming is similar to rtos real-time task creation, which saves resources more than processes

Thread header file
#include<pthread.h>

Function prototype
1. Create thread
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
Parameters: thread: thread id (output parameter)
attr: thread attributes, Generally set to NULL
tart_routine: thread function pointer
arg: generally set to NULL
Return value: success 0, error failure number

2. Thread waiting
int pthread_join(pthread_t thread, void **retval);
Parameters: thread: thread number tid
retval: waiting for the exit code of the thread
Return: success 0, failure failure number

Compilation needs to add -lpthread
such as gcc main.c -o main -lpthread

Code example


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

Guess you like

Origin blog.csdn.net/u010835747/article/details/105110336