- 一個應用程序可以啟動若干個線程;
- 線程,是程序執行的最小單位;
- 一般一個最簡單的程序最少有一個線程,就是程序本身,也是主函數;
- 一個線程阻塞不會影響另一個線程;
- 多線程的進程可以盡可能多的利用系統CPU資源。
/*** thread.c ***/ #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<unistd.h> int *thread(void *arg) { pthread_t newThid; newThid = pthread_self(); printf("this is a new thread,thread ID = %lu\n",newThid); return NULL; } int main() { int iRet = 0; pthread_t thid; printf("main thread,ID is %lu\n",pthread_self()); iRet = pthread_create(&thid,NULL,(void *)thread,NULL); if(iRet != 0) { printf("thread creation failed\n"); exit(1); } sleep(1); exit(0); }
Attention:編譯時需要加上-lpthread來連接libpthread.so動態庫,否則會報錯。
Int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void*(*start_routine)(void*),void *arg);
函數參數:
pthread_t 代表創建線程的唯一標識,是一個結構體,需要創建好以后將結構體的指針傳遞過去;
pthread_attr_t:代表創建這個線程的一些配置,比如分配棧的大小,一般設置位NULL,表示默認的創建線程的配置;
start_routine:代表一個函數的地址,創建線程時,會調用這個函數,函數的返回值時void*,函數的參數也是void*;
arg:代表調用第三個函數傳遞的參數。
函數的返回值:
函數成功返回0,不等於0表示函數調用失敗,此時可以通過strerror(error)可以打印出具體的錯誤。
ATTENTION:每個函數都有一份errno副本,不同的線程擁有不同的errno