linux本沒有線程的概念,它本身是一個(gè)”多進(jìn)程單線程”模型,所以linux線程的創(chuàng)建并不是天生的,它是用戶級(jí)上的一個(gè)概念。在創(chuàng)建線程時(shí),實(shí)際上是clone了父進(jìn)程的資源后另外創(chuàng)建的一個(gè)輕量級(jí)進(jìn)程,只不過表現(xiàn)起來像線程而已。因?yàn)椴皇莾?nèi)核自帶的功能,所以我們需要加入頭文件pthread.h并在編譯的時(shí)候加一項(xiàng)-lpthread來使用這一功能。
一、線程的創(chuàng)建
線程創(chuàng)建調(diào)用pthread_create,函數(shù)說明如下:
int pthread_create(
pthread_t*thread,
pthread_attr_t*attr,
void *(*start_routine)(void*)
,void *arg );
thread:當(dāng)線程創(chuàng)建成功,此結(jié)構(gòu)體包含該線程信息
attr:設(shè)置線程的屬性,一般設(shè)為NULL
start_routine:線程的回調(diào)函數(shù)
arg:線程回調(diào)所傳的參數(shù)
如果該函數(shù)調(diào)用成功,則返回0,否則返回錯(cuò)誤碼。
二、線程的退出
目前我所知的線程退出方法有三種:
線程自然退出
線程內(nèi)部調(diào)用pthread_exit()
使用pthread_cancel()函數(shù)
系統(tǒng)只會(huì)調(diào)用線程回調(diào)函數(shù)一次,函數(shù)執(zhí)行完畢,線程退出。在回調(diào)函數(shù)內(nèi)部也可以調(diào)用pthread_exit主動(dòng)結(jié)束線程調(diào)用,主動(dòng)結(jié)束調(diào)用時(shí)可以向pthread_exit傳入萬能參數(shù),讓外部使用pthread_join等待該線程退出的線程獲得它。最后一種我認(rèn)為比較暴力了,給我的感覺就像使用kill命令殺死進(jìn)程一樣,所以即使線程中存在死循環(huán)也能退出,使用該函數(shù)時(shí),一般配合pthread_join使用,防止發(fā)生段錯(cuò)誤。
三、pthread_join
此函數(shù)第二節(jié)也有提到,它需要傳入兩個(gè)參數(shù),一個(gè)是pthread_t結(jié)構(gòu)體,包含了線程的信息,第二個(gè)則是線程退出時(shí)返回的參數(shù),它的作用是使調(diào)用者阻塞,直至指定的線程退出。
附測(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");}