Linuxスレッドのプログラミング例

Linuxスレッドプログラミング

スレッドプログラミングは、RTOSのリアルタイムタスク作成に似ており、プロセスよりもリソースを節約できます。

スレッドヘッダーファイル
#include <pthread.h>

関数プロトタイプ
1.スレッドを作成します
int pthread_create(pthread_t * thread、const pthread_attr_t * attr、void *(* start_routine)(void *)、void * arg);
パラメーター:スレッド:スレッドID(出力パラメーター)
attr:スレッド属性、通常はNULLに設定
tart_routine:スレッド関数ポインタ
arg:通常はNULLに設定
戻り値:成功0、エラー失敗番号

2.スレッドは
int pthread_join(pthread_t thread、void ** retval);を待機します
パラメーター:スレッド:スレッド番号tid
retval:待機中のスレッドの終了コード
戻り値:成功0、失敗失敗番号

コンパイルでは
、gcc main.c -o main -lpthreadなどの-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