初识Linux C线程
線程與進程
進程是操作系統資源分配的基本單位,而線程是任務調度和執行的基本單位,線程在某種程度上可以看做輕量級的進程。
每個進程都有獨立的代碼和數據空間,程序間的切換會有較大開銷;同一組線程可以共享代碼和數據空間,每個線程仍具有自己獨立的運行棧和程序計數器,程序之間切換的開銷也較小。
由于線程共享進程地址空間的所有資源,所以線程之間的通信很方便;多個線程處理不同人物,增加了程序的并發性,是程序高效運行。
線程的創建
同進程一樣,每個線程都有自己的ID,使用的數據類型為pthread_t,其本質也是一種無符號整型。Linux下使用pthread_t pthread_self(void)函數得到一個線程的ID,包含在頭文件pthread.h中;進程的創建函數為int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg),第一個參數為指向存儲創建進程的ID變量的指針。第二個參數表示線程屬性,可置為NULL。第三個參數為一個函數指針,指向創建的線程的主體,即pthread_create()函數創建的線程從start_rtn所指向的函數的起始地址開始執行,當函數返回時該線程就停止運行了。如果線程創建成功了,函數返回0,若是失敗則返回錯誤編號,因此需要對錯誤編號進行識別。
編寫一個線程創建的例子:
#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(); //獲得本進程的進程IDtid = pthread_self(); //獲得本線程的線程IDprintf("the created thread: pid is %u, tid is %u \n", (unsigned int)pid, (unsigned int)tid); //打印獲得的進程、線程IDreturn NULL;
}
int main(){pid_t pid;int err; //聲明錯誤編號變量pthread_t mtid; //聲明線程變量pid = getpid(); mtid = pthread_self(); //獲取主線程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;
}
因為pthread庫不是Linux默認的庫,所以鏈接時需要用到libpthread.a,在編譯時加入-lpthread。編譯和運行結果:
創建的新線程只執行thfn()函數,執行之后線程就退出了,在執行過程中可以訪問進程資源。
線程的終止
線程的退出方式有:
- 線程函數執行結束,類似于進程中的main()函數返回(正常退出);
- 線程被另一個線程所取消,類似于進程中的kill(異常退出);
- 線程自行退出,類似于進程中調用exit()(異常退出);
Linux環境下使用pthread_cancel(pthread_t tid)函數取消一個線程,函數參數表示要取消的線程的ID,取消成功返回0,否則返回錯誤編號。
?
總結
以上是生活随笔為你收集整理的初识Linux C线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 女性不孕检查什么科
- 下一篇: 位序、字节序、类型序