ps aux -L 查看線程信息 且顯示進程狀態
?
?
使用進程的缺點: 進程切換 系統開銷較大
開銷大的原因 :切換時需要頻繁刷新 cache(類似于緩沖區) 和TLB
?
linux不區分線程 進程
?
線程其實也屬于進程 只不過是特殊的進程 是一種可以共享地址空間的進程
?
使用線程的優點:同一進程的線程會共享相同的地址空間
當使用多線程時 會大大提高任務切換的效率
避免多次刷新cache和TLB
通過全局變量即可交換數據 使通信變得非常容易
缺點:
多個線程訪問共享資源時 需要同步或互斥機制
?
一個進程中的線程可共享的資源:
?
可執行指令
靜態數據
進程中打開的文件描述符
當前工作目錄
用戶D
用戶組ID
?
每個線程私有的資源:
線程ID
pc(程序計數器)和相關寄存器
堆棧
錯誤號
優先級
執行狀態和屬性
?
?????????????????????????????????????????????????????????????? 創建線程
?
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*routine)(void *), void *arg);
成功返回0 失敗返回錯誤碼
thread 線程對象
attr 指定線程屬性 NULL代表默認屬性
routine 線程執行函數 (參數是一個函數指針)
arg 傳遞給routine這個函數的參數
?
?????????????????????????????????????????? 線程回收
?
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval)
?
成功返回0 失敗返回錯誤碼
thread 要回收的線程對象 如果線程未結束 調用線程會阻塞 直到thread結束
*retval 接受線程的返回值
?
???????????????????????????????????????????????????????????????? 結束線程
?
#include <pthread.h>
void pthread_exit(void *retval)
?
如果用exit()會結束所有線程
retval可別其他線程通過pthread_join()獲取
retval需要被設定成全局變量才能被其他進程操作 否則只能被當前進程操作
?
Ps:
char message[32] = {"hello world!"}
void *thread_func(void *arg); //創建進程參數的實現函數
?
int main()
{
pthread_t a_thread;
void *result;
?
if(pthread_create(&a_thread, NULL, thread_func), NULL) != 0)
{
printf("fail to pthread_creat");
exit(-1);
}
?
pthread_join(&a_thread, &result);
printf("result is %s\n", result);
printf("message is %s\n", message);
return 0;
}
?
//重寫實現函數
void thread_func(void *arg)
{
sleep(1);
strcpy(message, "marked by thread");
pthread_exit("thank you for waiting for me");
}
?
運行命令:
gcc -o test test.c -lpthread
./test
打印結果:
thank you to waiting for me
marked by thread
?
?
?