Linux thread concept introduction and programming realization

#include <stdio.h>

void func1()
{
    
    
	while(1){
    
    
		printf("This is func1\n");
		sleep(1);
		}
}

void func2()
{
    
    
	while(1){
    
    
		printf("This is func2\n");
		sleep(1);
		}
}

int main()
{
    
    
	func1();
	func2();
	return 0;
}

In the above code, we can know that the while(1) infinite loop is set in the two functions, so only the func1() function can be executed in the main function.

To run func1() and func2() at the same time, Linux threads are needed.


Thread code example:

#include <stdio.h>
#include <pthread.h>
void* thread( void *arg )
{
    
    
    printf( "This is a thread and arg = %d.\n", *(int*)arg);
    *(int*)arg = 0;
    return arg;
}
int main( int argc, char *argv[] )
{
    
    
    pthread_t th;
    int ret;
    int arg = 10;
    int *thread_ret = NULL;
    ret = pthread_create( &th, NULL, thread, &arg );	//第一个是线程描述符;第二个一般写NULL;第三个是线程;第四个是函数的参数
    if( ret != 0 ){
    
    
        printf( "Create thread error!\n");
        return -1;
    }
    printf( "This is the main process.\n" );
    pthread_join( th, (void**)&thread_ret );
    printf( "thread_ret = %d.\n", *thread_ret );
    return 0;
}

Note: When running a thread program in a Linux terminal, you need to link the pthread library, so you need to add -lpthread to run the program

gcc **.c -lphread

So modify the original example code:

#include <stdio.h>
#include <pthread.h>	//需要声明此库

void *func1()		   //需要加个*
{
    
    
	while(1){
    
    
		printf("This is func1\n");
		sleep(1);
		}
}

void func2()
{
    
    
	while(1){
    
    
		printf("This is func2\n");
		sleep(1);
		}
}

int main()
{
    
    
	pthread_t, th1;
	pthread_create(&th1, NULL, func1, NULL);
	//func1();
	func2();
	return 0;
}

Running the modified code will allow the two functions to run simultaneously.

You can also create two threads:

#include <stdio.h>
#include <pthread.h>	//需要声明此库

void *func1()		   //需要加个*
{
    
    
	while(1){
    
    
		printf("This is func1\n");
		sleep(1);
		}
}

void *func2()
{
    
    
	while(1){
    
    
		printf("This is func2\n");
		sleep(1);
		}
}

int main()
{
    
    
	pthread_t, th1;
	pthread_t, th2;
	pthread_create(&th1, NULL, func1, NULL);	//第二个线程
	phtread_create(&th2, NULL, func2, NULL);	//第三个线程
	//func1();
	//func2();
	while(1);	//主线程
	return 0;
}

Guess you like

Origin blog.csdn.net/zouchengzhi1021/article/details/112837889