linux本沒(méi)有線(xiàn)程的概念育瓜,它本身是一個(gè)”多進(jìn)程單線(xiàn)程”模型,所以linux線(xiàn)程的創(chuàng)建并不是天生的,它是用戶(hù)級(jí)上的一個(gè)概念仑荐。在創(chuàng)建線(xiàn)程時(shí),實(shí)際上是clone了父進(jìn)程的資源后另外創(chuàng)建的一個(gè)輕量級(jí)進(jìn)程纵东,只不過(guò)表現(xiàn)起來(lái)像線(xiàn)程而已粘招。因?yàn)椴皇莾?nèi)核自帶的功能,所以我們需要加入頭文件pthread.h并在編譯的時(shí)候加一項(xiàng)-lpthread來(lái)使用這一功能偎球。
一洒扎、線(xiàn)程的創(chuàng)建
線(xiàn)程創(chuàng)建調(diào)用pthread_create,函數(shù)說(shuō)明如下:
int pthread_create(
pthread_t*thread,
pthread_attr_t*attr,
void *(*start_routine)(void*)
,void *arg );
thread:當(dāng)線(xiàn)程創(chuàng)建成功,此結(jié)構(gòu)體包含該線(xiàn)程信息
attr:設(shè)置線(xiàn)程的屬性衰絮,一般設(shè)為NULL
start_routine:線(xiàn)程的回調(diào)函數(shù)
arg:線(xiàn)程回調(diào)所傳的參數(shù)
如果該函數(shù)調(diào)用成功袍冷,則返回0,否則返回錯(cuò)誤碼猫牡。
二胡诗、線(xiàn)程的退出
目前我所知的線(xiàn)程退出方法有三種:
線(xiàn)程自然退出
線(xiàn)程內(nèi)部調(diào)用pthread_exit()
使用pthread_cancel()函數(shù)
系統(tǒng)只會(huì)調(diào)用線(xiàn)程回調(diào)函數(shù)一次,函數(shù)執(zhí)行完畢,線(xiàn)程退出煌恢。在回調(diào)函數(shù)內(nèi)部也可以調(diào)用pthread_exit主動(dòng)結(jié)束線(xiàn)程調(diào)用骇陈,主動(dòng)結(jié)束調(diào)用時(shí)可以向pthread_exit傳入萬(wàn)能參數(shù),讓外部使用pthread_join等待該線(xiàn)程退出的線(xiàn)程獲得它瑰抵。最后一種我認(rèn)為比較暴力了你雌,給我的感覺(jué)就像使用kill命令殺死進(jìn)程一樣,所以即使線(xiàn)程中存在死循環(huán)也能退出二汛,使用該函數(shù)時(shí)婿崭,一般配合pthread_join使用,防止發(fā)生段錯(cuò)誤习贫。
三逛球、pthread_join
此函數(shù)第二節(jié)也有提到,它需要傳入兩個(gè)參數(shù)苫昌,一個(gè)是pthread_t結(jié)構(gòu)體,包含了線(xiàn)程的信息幸海,第二個(gè)則是線(xiàn)程退出時(shí)返回的參數(shù)祟身,它的作用是使調(diào)用者阻塞,直至指定的線(xiàn)程退出物独。
附測(cè)試用例:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void *thread_function(void *arg);
char message[] = "Hello World";
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_function, (void*)message);
if (res != 0)
{
perror("Thread creation failed!\n");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finish...\n");
//res = pthread_join(a_thread, &thread_result);
//if (res != 0){
//perror("Thread joinfailed!\n");
//exit(EXIT_FAILURE);
//}
//sleep(3);
pthread_cancel(a_thread);
//pthread_join(a_thread,&thread_result);
printf("Thread joined, it returned \n");
printf("Message is now %s\n", message);
exit(EXIT_FAILURE);
}
void *thread_function(void *arg)
{
printf("thread_function is running. Argument was %s\n", (char*)arg);
//sleep(3);
strcpy(message, "Bye!\n");
while(1)
{}//pthread_exit((void*)"Thank you for your CPU time!\n");}