Linux C 多线程函数
POSIX 线程
POSIX线程(POSIX Threads),简写为 Pthreads,是POSIX的线程标准,定义了创建和操纵线程的一套API。一般多用于类 Unix 操作系统。
Pthreads 定义了一套C语言的类型、函数与常量,它以 <pthread.h> 头文件和一个线程库实现。
Pthreads API中大致共有100个函数调用,全都以"pthread_"开头,并可以分为四类:
- 线程管理,例如创建线程,等待(join)线程,查询线程状态等。
- 互斥锁(Mutex):创建、摧毁、锁定、解锁、设置属性等操作
- 条件变量(Condition Variable):创建、摧毁、等待、通知、设置与查询属性等操作
- 使用了互斥锁的线程间的同步管理
线程管理函数
-
pthread_create - create a new thread
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
创建成功返回 0;创建失败返回 error 值,并且 *thread 不会被定义
-
pthread_exit - terminate calling thread
void pthread_exit(void *retval);
终止正在调用的线程,并且返回通过 retval 返回值,如果该线程在调用pthread_join的同一进程中可用于另一个线程
-
pthread_join - join with a terminated thread
int pthread_join(pthread_t thread, void **retval);
等待指定的线程终止,如果需要可通过 retval 获取线程的终止状态
-
pthread_cancel - send a cancellation request to a thread
int pthread_cancel(pthread_t thread);
发送一个消除线程的请求。线程可通过 pthread_cancel 函数来请求取消同一进程中的其他线程
-
pthread_detach - detach a thread
int pthread_detach(pthread_t thread);
分离一个线程
-
pthread_cleanup_push - push thread cancellation clean-up handlers
void pthread_cleanup_push(void (*routine)(void *), void *arg);
调度线程清理函数 routine,调用时只有一个参数 arg
-
pthread_cleanup_pop - pop thread cancellation clean-up handlers
void pthread_cleanup_pop(int execute);
删除上次由 pthread_cleanup_push 调用建立的清理处理程序。如果 execute 为 0,清理函数不会被调用
-
pthread_equal - compare thread IDs
int pthread_equal(pthread_t t1, pthread_t t2);
如果两个线程 ID 相等返回非 0 值,不相等返回 0