1.背景知識
Linux沒有真正意義上的線程,它的實現是由進程來模擬,所以屬於用戶級線程,位於libpthread共享庫(所以線程的ID只在庫中有效),遵循POSIX標準。
Windows下有一個真正的數據結構TCB來描述線程。
Linux上兩個最有名的線程庫LinuxThreads和NPTL。
Linux兩個線程模型的比較:
Linux下多線程虛擬地址空間的映射類似於用vfork創建多個子進程。
2.進程和線程的區別
進程:程序的一個動態運行實例,承擔分配系統資源的實例。(Linux實現進程的主要目的是資源獨佔)線程:在進程的內部運行(進程的地址空間)運行的一個分支,也是調度的基本單位(調度按LWP調度)。(Linux實現線程的主要目的是資源共享)
線程所有的資源由進程提供。
單進程:只有一個進程的線程(LWP=PID)。
LWP:輕量級進程。
由於同一進程的多個線程共享同一地址空間,因 此Text Segment、Data Segment都是共享的,如果定義一個函數,在各線程中都可以調用,如果定義一個全局變量,在各線程中都可以訪問到,除此之外,各線程還共享以下進程資源和環境:
1. 文件描述符表2. 每種信號的處理方式(SIG_IGN、SIG_DFL或者自定義的信號處理函數)3. 當前工作目錄4. 用戶id和組id
1.線程ID2. 上下文信息,包括各種寄存器的值、程序計數器和棧指針3. 棧空間4. errno變量5. 信號屏蔽字6. 調度優先級
多線程程序的優點(相對進程比較而言):
3.進程控制
創建線程函數———pthread_create函數
- #include <pthread.h>
- int pthread_create(pthread_t * thread, const pthread_arrt_t* attr,void*(*start_routine)(void *), void* arg);
(1)thread參數是新線程的標識符,爲一個整型。
終止線程———pthread_cancel函數和pthread_exit函數
- #include <pthread.h>
- int pthread_cancel(pthread_t thread);
- #include <pthread.h>
- void pthread_exit(void * retval);
線程等待———pthread_join
- #include <pthread.h>
- void pthread_join(pthread_t thread,void ** retval);
(例如棧)是不釋放的。(默認情況下線程的創建都是可結合的)
- #include <stdio.h>
- #include <error.h>
- #include <stdlib.h>
- #include <pthread.h>
- void* thread_run(void* _val)
- {
- pthread_detach(pthread_self()); //註釋這句代碼join success
- printf("%s\n", (char*)_val);
- return NULL;
- }
-
-
- int main()
- {
- pthread_t tid;
- int tret = pthread_create(&tid, NULL, thread_run, "thread_run~~~~~");
- //線程創建成功之後,程序的執行流變成兩個,一個執行函數thread_run,一個繼續向下執行。
- if (tret == 0)
- {
- sleep(1);
- int ret = pthread_join(tid, NULL);
- if (ret == 0)
- {
- printf("pthread_join success\n");
- return ret;
- }
- else
- {
- printf("pthread_join failed info: %s\n", strerror(ret));
- return ret;
- }
- }
- else
- {
- printf("create pthread failed info: %s", strerror(tret));
- return tret;
- }
- }
運行結果:
轉載:https://blog.csdn.net/skyroben/article/details/72793409