初识Linux C线程
線(xiàn)程與進(jìn)程
進(jìn)程是操作系統(tǒng)資源分配的基本單位,而線(xiàn)程是任務(wù)調(diào)度和執(zhí)行的基本單位,線(xiàn)程在某種程度上可以看做輕量級(jí)的進(jìn)程。
每個(gè)進(jìn)程都有獨(dú)立的代碼和數(shù)據(jù)空間,程序間的切換會(huì)有較大開(kāi)銷(xiāo);同一組線(xiàn)程可以共享代碼和數(shù)據(jù)空間,每個(gè)線(xiàn)程仍具有自己獨(dú)立的運(yùn)行棧和程序計(jì)數(shù)器,程序之間切換的開(kāi)銷(xiāo)也較小。
由于線(xiàn)程共享進(jìn)程地址空間的所有資源,所以線(xiàn)程之間的通信很方便;多個(gè)線(xiàn)程處理不同人物,增加了程序的并發(fā)性,是程序高效運(yùn)行。
線(xiàn)程的創(chuàng)建
同進(jìn)程一樣,每個(gè)線(xiàn)程都有自己的ID,使用的數(shù)據(jù)類(lèi)型為pthread_t,其本質(zhì)也是一種無(wú)符號(hào)整型。Linux下使用pthread_t pthread_self(void)函數(shù)得到一個(gè)線(xiàn)程的ID,包含在頭文件pthread.h中;進(jìn)程的創(chuàng)建函數(shù)為int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg),第一個(gè)參數(shù)為指向存儲(chǔ)創(chuàng)建進(jìn)程的ID變量的指針。第二個(gè)參數(shù)表示線(xiàn)程屬性,可置為NULL。第三個(gè)參數(shù)為一個(gè)函數(shù)指針,指向創(chuàng)建的線(xiàn)程的主體,即pthread_create()函數(shù)創(chuàng)建的線(xiàn)程從start_rtn所指向的函數(shù)的起始地址開(kāi)始執(zhí)行,當(dāng)函數(shù)返回時(shí)該線(xiàn)程就停止運(yùn)行了。如果線(xiàn)程創(chuàng)建成功了,函數(shù)返回0,若是失敗則返回錯(cuò)誤編號(hào),因此需要對(duì)錯(cuò)誤編號(hào)進(jìn)行識(shí)別。
編寫(xiě)一個(gè)線(xiàn)程創(chuàng)建的例子:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
#include<errno.h>
void *thfn(void *arg){pid_t pid;pthread_t tid;pid = getpid(); //獲得本進(jìn)程的進(jìn)程IDtid = pthread_self(); //獲得本線(xiàn)程的線(xiàn)程IDprintf("the created thread: pid is %u, tid is %u \n", (unsigned int)pid, (unsigned int)tid); //打印獲得的進(jìn)程、線(xiàn)程IDreturn NULL;
}
int main(){pid_t pid;int err; //聲明錯(cuò)誤編號(hào)變量pthread_t mtid; //聲明線(xiàn)程變量pid = getpid(); mtid = pthread_self(); //獲取主線(xiàn)程IDprintf("The main thread: pid is %u, tid is %u \n", (unsigned int)pid, (unsigned int)mtid);err = pthread_create(&mtid, NULL, thfn, NULL);if(err != 0){printf("Can't create thread %s\n", strerror(err));exit(1);}sleep(1);printf("The created thread: pid is %u, tid is %u \n", (unsigned int)pid, (unsigned int)mtid);mtid = pthread_self();printf("The main thread: pid is %u, tid is %u \n", (unsigned int)pid, (unsigned int)mtid);return 0;
}
因?yàn)閜thread庫(kù)不是Linux默認(rèn)的庫(kù),所以鏈接時(shí)需要用到libpthread.a,在編譯時(shí)加入-lpthread。編譯和運(yùn)行結(jié)果:
創(chuàng)建的新線(xiàn)程只執(zhí)行thfn()函數(shù),執(zhí)行之后線(xiàn)程就退出了,在執(zhí)行過(guò)程中可以訪問(wèn)進(jìn)程資源。
線(xiàn)程的終止
線(xiàn)程的退出方式有:
- 線(xiàn)程函數(shù)執(zhí)行結(jié)束,類(lèi)似于進(jìn)程中的main()函數(shù)返回(正常退出);
- 線(xiàn)程被另一個(gè)線(xiàn)程所取消,類(lèi)似于進(jìn)程中的kill(異常退出);
- 線(xiàn)程自行退出,類(lèi)似于進(jìn)程中調(diào)用exit()(異常退出);
Linux環(huán)境下使用pthread_cancel(pthread_t tid)函數(shù)取消一個(gè)線(xiàn)程,函數(shù)參數(shù)表示要取消的線(xiàn)程的ID,取消成功返回0,否則返回錯(cuò)誤編號(hào)。
?
總結(jié)
以上是生活随笔為你收集整理的初识Linux C线程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 女性不孕检查什么科
- 下一篇: 《听歌六绝句·离别难》第二句是什么