1、創建線程/等待線程結束
1、pthread_create函數
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
//功能:用於創建一個線程
//參數1:線程號
//參數2:創建線程時需要設置的屬性,如果爲NULL則按默認的方式進行創建
typedef union
{
char __size[__SIZEOF_PTHREAD_ATTR_T];
long int __align;
}pthread_attr_t;
//參數3:函數指針,表示線程的入口函數
//參數4::給線程的入口函數傳遞的參數
2、pthread_join函數
int pthread_join(pthread_t thread, void **retval);
//功能:等待線程結束
//參數1:線程號
//參數2:指針變量的地址,用於獲取入口函數的返回值,如果入口函數沒有返回值則設置爲NULL
舉例:
#include <stdio.h>
#include <pthread.h>
//線程的入口函數
void* start_run(void* arg)
{
int* num = (int*)arg;
//在線程中我們將這個參數加10並返回
*num += 10;
return num;
}
int main()
{
pthread_t pid;
//按照默認方式來執行,線程的入口函數爲start_run,入口函數的參數爲a
int a = 100;
pthread_create(&pid,NULL,start_run,&a);
printf("before end a = %d\n",a);
void* p = NULL;
pthread_join(pid,&p);
printf("after end a = %d\n",*(int*)p);
}
運行效果