Linux下線程裏面可以再創建線程嗎?是的,可以

Linux下線程裏面可以再創建線程嗎

經過操作系統的學習,我們知道線程是系統調用的最小單位,不是資源分配的最小單位,那麼,線程裏面可以創建新的線程嗎?

因爲我在項目中使用線程再創建線程出現了問題,因此產生這個疑惑,經過嘗試之後發現,線程裏面是可以再創建線程的,具體實例代碼如下:

#include <limits.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

typedef struct 
{
	int num;
	char* str;
}pere_Data;

void* work(int num,char* str)
{
	printf("The num is %d\n",num);
	printf("The str is %s\n",str);
}

void* fun(int num)
{
		printf("********The num is: %d*********\n",num);
}


void* thread_func(void *argv)
{
	pere_Data *p = (pere_Data*)argv;

	//線程響應
	work(p->num,p->str);
	
	pthread_t tid;
	int num = 6;
	pthread_create(&tid,NULL,fun,num);

	pthread_join(tid,NULL);
	pthread_exit(0);
}

int main()
{
		pthread_t pid;
		pere_Data p;
		p.num = 10;
		p.str = "hello";
					
		pthread_create(&pid,NULL,thread_func,(void *)&p);
		pthread_join(pid,NULL);
		printf("==============\n");
}

初學者需要注意的是,在編譯的時候,編譯指令後需要後綴-lpthread

程序運行結果如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章