文章目录
  1. 创建线程
  2. 结束线程
  3. 回收线程
  4. 异常终止

创建线程

创建一个线程使用函数pthread_create,其定义如下。

1
2
3
4
5
6
7
8
9
/*
引用方式: #include <pthread.h>
th: 新线程标识符(pthread_t即整型)
attr: 设置新线程的属性(默认为NULL, 即使用默认线程属性
func: 指定新线程运行的函数
arg: 指定运行的函数参数
返回0: 成功 || 返回错误码: 失败
*/
int pthread_create(pthread_t th, const pthread_attr_t * attr, void * (* func)(void *), void * arg);

一个用户可打开的线程数量不能超过RLIMIT_NPROC软资源限制;此外,系统上所有用户能创建的线程总数也不能超过/proc/sys/kernal/threads-max内核参数所定义的值。

线程创建好之后,内核将调度内核线程来执行func所指向的函数。

结束线程

线程函数在结束时推荐调用pthread_exit,以保证线程安全、干净的退出。

1
2
3
4
5
/*
引用方式: #include <pthread.h>
retval: 指定线程的回收者
*/
void pthread_exit(void * retval);

pthread_exit向线程的回收者传递其退出信息,它执行完后不会返回调用者,永远不会失败。

回收线程

一个进程的所有线程都可以调用pthread_join函数来回收其他线程(前提是目标线程可回收),即等待其他线程结束,pthread_join函数定义如下。

1
2
3
4
5
6
7
/*
引用方式: #include <pthread.h>
th: 目标线程标识符
retval: 存储目标线程返回的退出信息
返回0: 成功 || 返回错误码: 失败
*/
int pthread_join(pthread_t th, void * * retval);

pthread_join函数会一直阻塞直到被回收的线程结束。

pthread_join可能引发如下错误码。

异常终止

若一个线程希望异常终止另一个线程,即取消线程。可使用pthread_cancel函数实现。

1
2
3
4
5
6
/*
引用方式: #include <pthread.h>
th: 目标线程标识符
返回0: 成功 || 返回错误码: 失败
*/
int pthread_cancel(pthread_t th);

接收到取消请求的目标线程可以决定是否允许被取消以及如何取消。分别由如下两个函数实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
引用方式: #include <pthread.h>
state: 设置线程的取消状态; PTHREAD_CANCEL_ENABLE: 允许线程被取消 || PTHREAD_CANCEL_DISABLE: 禁止线程被取消
type: 设置线程的取消类型
PTHREAD_CANCEL_ASYNCHRONOUS: 线程随时被取消目标线程将立即采取行动
PTHREAD_CANCEL_DEFERED: 允许目标线程推迟行动直到它调用取消点函数pthread_testcancle函数
old_state: 存储线程之前的取消状态
old_type: 存储线程之前的取消类型
返回0: 成功 || 返回错误码: 失败
*/
int pthread_setcancelstate(int state, int * old_state);

int pthread_setcanceltype(int type, int * old_type);