Linux多线程实践(2) --线程基本API
POSIX線程庫
? 與線程有關的函數構成了一個完整的系列,絕大多數函數的名字都是以“pthread_”開頭,要使用這些函數庫,要通過引入頭文<pthread.h>,而且鏈接這些線程函數庫時要使用編譯器命令的“-lpthread”選項[Ubuntu系列系統需要添加的是”-pthread”選項而不是”-lpthread”,如Ubuntu?14.04版本,深度Ubuntu等]
?
1.pthread_create
int pthread_create(pthread_t *restrict thread,const pthread_attr_t *restrict attr,void *(*start_routine)(void*), void *restrict arg);創建一個新的線程
參數
? thread:線程ID
??attr:設置線程的屬性,一般設置為NULL表示使用默認屬性
??start_routine:是個函數地址,線程啟動后要執行的函數
??arg:傳給線程啟動函數的參數
返回值:成功返回0;失敗返回錯誤碼;
?
附-Posix錯誤檢查
??UNIX傳統的函數:成功返回0,失敗返回-1,并且對設置全局變量errno以指定錯誤類型。然而pthreads函數出錯時不會設置全局變量errno(而其他的大部分POSIX函數會設置errno)。而是將錯誤代碼通過返回值返回;
??pthreads同樣也提供了線程內的errno變量,對于每一個線程,?都有一個errno的值,?以支持其它使用errno的代碼。對于pthreads函數的錯誤,建議通過返回值進行判定,因為讀取返回值要比讀取線程內的errno變量的開銷更小!
/** 實踐: 新的錯誤檢查與錯誤退出函數 **/ inline void err_check(const std::string &msg, int retno) {if (retno != 0)err_exit(msg, retno); } inline void err_exit(const std::string &msg, int retno) {std::cerr << msg << ": " << strerror(retno) << endl;exit(EXIT_FAILURE); }2.pthread_exit
void pthread_exit(void *value_ptr);線程終止
? value_ptr:指向該線程的返回值;注意:value_ptr不能指向一個局部變量。
?
3.pthread_join
int pthread_join(pthread_t thread, void **value_ptr);等待線程結束
??value_ptr:它指向一個指針,后者指向線程的返回值(用戶獲取線程的返回值)
/** 示例: 等待線程退出 **/ void *thread_rotine(void *args) {for (int i = 0; i < 10; ++i){printf("B");fflush(stdout);usleep(20);}pthread_exit(NULL); }int main() {pthread_t thread;int ret = pthread_create(&thread, NULL, thread_rotine, NULL);err_check("pthread_create", ret);for (int i = 0; i < 10; ++i){printf("A");fflush(stdout);usleep(20);}ret = pthread_join(thread, NULL);err_check("pthread_join", ret);putchar('\n');return 0; }4.pthread_self
pthread_t pthread_self(void);返回線程ID
/** 示例:主控線程與子線程傳遞數據 **/ typedef struct _Student {char name[20];unsigned int age; } Student;void *threadFunction(void *args) {cout << "In Thread: " << pthread_self() << endl;Student tmp = *(Student *)(args);cout << "Name: " << tmp.name << endl;cout << "Age: " << tmp.age << endl;pthread_exit(NULL); }int main() {Student student = {"xiaofang",22};pthread_t thread;//啟動創建并啟動線程pthread_create(&thread,NULL,threadFunction,&student);//等待線程結束pthread_join(thread,NULL);return 0; }5.pthread_cancel
int pthread_cancel(pthread_t thread);取消一個執行中的線程
6.pthread_detach
int pthread_detach(pthread_t thread);??將一個線程分離-如果在新創建的線程結束時主線程沒有結束同時也沒有調用pthread_join,則會產生僵線程,次問題可以通過設置線程為分離的(detach)來解決;
?
總結:進程 VS.?線程
進程(pid_t) | 線程(pthread_t) |
Fork | Pthread_create |
Waitpit | Pthread_join/Pthread_detach |
Kill | Pthread_cancel |
Pid | Pthead_self |
Exit/return | Pthread_exit/return |
僵尸進程(沒有調用wait/waitpid等函數) | 僵尸線程(沒有調用pthread_join/pthread_detach) |
其完整源代碼:download.csdn.net/detail/hanqing280441589/8440763
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!
總結
以上是生活随笔為你收集整理的Linux多线程实践(2) --线程基本API的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用cx_Freeze将py文件打包成e
- 下一篇: linux 其他常用命令