线程 | 进程 | |
标识符 | 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); 非零参数