線程 | 進程 | |
標識符 | pthread_t | pid_t |
獲取ID | pthread_self() | getpid() |
建立 | pthread_create() | fork |
銷燬 | pthread_exit() | exit() |
等待 | pthread_join() | wait() |
取消 | pthread_cancel() | |
信號發送 | pthread_kill() | kill() raise() alarm() |
信號處理 | signal | signal |
信號屏蔽 | pthread_sigmask() | |
線程清除 | pthread_cleanup_push/pop |
1.線程的建立安全
#include <pthread.h> pthread_t pthread_self(void); //返回本身的線程id int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); //pthread_t *thread 新線程的id指針,注意是指針, pthread_t ntid; 這裏就是 &tid //const pthread_attr_t *attr, 新線程屬性,這裏暫爲NULL //void *(*start_routine) (void *), 新線程的函數入口 /* * 描述:這是一個函數指針做爲入口函數 * 參數:void * 指針類型 * 返回值爲 void* * (*start_routine) 這是一個指針變量,它指向一個函數, 所以在實參裏本應該是&thread_fun 可是由於 函數名編譯後,自己就是指針,因此能夠隱去& */ //實例:pthread_creat(&ntid,NULL,&thread_fun,"我是給thread_fun的參數"); // void *thread_fun(void *arg){} void pthread_exit(void *value_ptr);
2.線程的終止app
單個線程的安全退出 (3) (1) 從啓動線程中返回,返回值時線程的退出碼 (2) 線程能夠被同一進程中的其餘線程取消 (3) 線程調用pthread_exit(void *rval),rval 是退出碼 void pthread_exit(void *value_ptr);
3.線程的連接函數
#include <pthread.h> int pthread_join(pthread_t thread, void **value_ptr); //該函數的線程會一直阻塞,直到 第一個參數的線程退出後,繼續運行,第一個參數的線程退出碼會被保存到第二個參數裏, //return 成功0 失敗錯誤嗎 //調用pthread_join 會讓指定的線程處於分離狀態,若是該線程已是分離狀態,那就會調用失敗。 // int pthread_detach(pthread_t thread); //線程分離,能夠分離本身
4.線程取消spa
//取消線程 int pthread_cancel(pthread_t thread); //取消狀態 int pthread_setcancelstate(int state, int *oldstate); //PTHREAD_CANCEL_ENABLE 容許取消 //PTHREAD_CANCEL_DISABLE 不容許取消 //取消類型 int pthread_setcanceltype(int type, int *oldtype); //PTHREAD_CANCEL_DEFERRED 延遲取消 //PTHREAD_CANCEL_ASYNCHRONOUS 當即取消 //取消點 若是是延時取消,那麼在每個取消點都會檢查是否取消
5.線程信號線程
//1.信號的發送 int pthread_kill(pthread_t thread, int sig); //向線程發送信號 //return // [ESRCH] thread is an invalid thread ID. // [EINVAL] sig is an invalid or unsupported signal number. //[ENOTSUP] thread was not created by pthread_create() and does not support being killed with pthread_kill() //信號的大部分操做是終止進程,因此要對信號做出正確的處理。
//2.信號的處理 int sigaction(int sig, const struct sigaction *restrict act, struct sigaction *restrict oact); struct sigaction { union __sigaction_u __sigaction_u; /* signal handler */ sigset_t sa_mask; /* signal mask to apply */ int sa_flags; /* see signal options below */ }; union __sigaction_u { void (*__sa_handler)(int); void (*__sa_sigaction)(int, siginfo_t *, void *); };
//3.信號的屏蔽 int pthread_sigmask(int how, const sigset_t * restrict set, sigset_t * restrict oset);
6.進程的清除指針
//線程能夠註冊多個清理程序,入棧的形式 ,因此執行順序和註冊順序相反 //註冊清理程序 void pthread_cleanup_push(void (*cleanup_routine)(void *), void *arg); //銷燬清理程序 void pthread_cleanup_pop(int execute); //響應方式 //1.pthreat_exit //2.pthread_cancel //3.調用 void pthread_cleanup_pop(int execute); 非零參數