一、线程概念: thread
- 轻量级进程 (Lightweight Process, LWP)
- 程序执行流的最小单元
- 操作系统能够进行运算调度的最小单位
- Linux 环境下,没有真正意义上的线程,
操作系统看到的是一个个的轻量级进程。
二、如何描述一个线程
既然线程是轻量级进程,那进程 PCB 自然是描述一个进程最好的方式了,我们来看看线程的 PCB 至少应该包含那些信息:
- 线程ID ---- 线程标识
(1) 一个非负整数
(2) 线程 ID 只有在该线程所属的进程上下文中才有意义
(3) 用 pthread_t 数据类型表示
(4) typedef unsigned long int pthread_t;
(5) 比较两个线程ID 是否相等
#include <pthread.h>
int pthread_equal(pthread_t tid1, pthread_t tid2);
// 返回值:若相等 返回非 0 数值 否则 返回 0
(6) 获取自身线程 ID
#include <pthread.h>
pthread_t pthread_self(void);
// 返回值: 调用线程的线程 ID- 一组寄存器值
- 栈
- 调度优先级和策略
- 信号屏蔽字
- errno 变量
- 线程私有数据
三、线程创建
在传统 UNIX进程模型中,每个进程只有一个控制线程。
新增的线程可以通过调用 pthread_create 函数创建
#include <pthread.h>
int
pthread_create
(
pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg
);
当 pthread_create 成功返回时
- 参数 thread (一个输出型参数): 新创建线程的线程 ID
- 参数 attr :用于定制各种不同的线程属性
默认 NULL - 参数 start_routine: 函数指针
新创建的线程从 start_routine函数的地址开始执行。
启动例程!!! - 参数 arg
start_routine 函数只有一个无类型参数 arg
如果需要向 start_routine 函数传递的参数有一个以上,那么把这些参数放到一个结构中,然后把这个结构的地址作为 arg 参数传入。 - 返回值: 若成功 返回 0
否则,返回错误编号
- 线程创建时并不能保证哪个线程先运行
- 新创建的线程可以访问进程的地址空间,并且继承调用线程的浮点环境和信号屏蔽字,但是该线程的挂起信号集会被清除
- 每个线程都提供 errno 副本,但是 errno是一个全局变量,说明不了问题。
我们写一个简单的测试程序来打印线程的线程 ID
// filename: print_thread_id.c
// 打印线程 ID
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t tid;
void print_id(const char * msg);
void * thr_fn(void * arg);
int main()
{
int err = 0;
err = pthread_create(&tid, NULL, thr_fn, NULL);
if(err != 0)
{
perror("pthread_create error");
exit(1);
}
print_id("main thread: ");
sleep(1); // 保证新线程有机会执行
// 如果主线程不休眠,它就可能退出,这样新线程还没有
// 机会运行,整个进程可能就已经终止了
return 0;
}
void print_id(const char * msg)
{
pid_t pid = 0;
pthread_t tid1 = 0;
pid = getpid();
tid1 = pthread_self();
printf("%s pid %lu tid %lu (0x%lx)\n", msg, (unsigned long)pid, (unsigned long)tid1, (unsigned long)tid1);
}
void * thr_fn(void * arg)
{
(void)arg;
printf("哈哈,我是新线程 tid = %lu\n", (unsigned long)pthread_self());
print_id("new thread: ");
return ((void *)0);
}
编译环境:CentOS 7
运行结果:
四、线程终止
1.线程终止
单个线程可以通过 3 种方式退出,因此可以在不终止整个进程的情况下,停止它的控制流。
(1) 从启动例程中返回,返回值是线程的退出码。
(2) 可以被同一进程的其他线程取消
(3) 调用 pthread_exit
#include <pthread.h>
void pthread_exit(void *retval);
参数 retval 是一个无类型指针
2.线程等待
但是我们知道,创建一个线程之后,如果主线程很快结束,那么新创建的线程没有机会执行就结束了,这不符合我们的初衷,于是我们调用 pthread_join 函数,它将会一直等待直到等待的线程结束自己才结束。
#include <pthread.h>
int pthread_join(pthread_t thread,
void **retval);
调用线程将一直阻塞,直到满足下列条件中的一个:
- 指定线程调用 pthread_exit
- 从启动例程返回
- 被其他线程取消
参数 thread 是线程 ID
如果线程简单的从启动例程返回,参数 retval 就包含返回码。
如果线程被取消,由 retval 指定的内存单元就设置为
PTHRAED_CANCELED。
如果不关心线程的返回值,可以把 retval 设置为 NULL。
我们写个简单的程序来获取已终止线程的退出码:
// filename: get_TerminatedThread_ExitCode.c
// 获取已终止线程的退出码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * thr_fun1(void * arg);
void * thr_fun2(void * arg);
int main(void)
{
int err = 0;
pthread_t tid1 = 0, tid2 = 0;
void * ret = NULL;
err = pthread_create(&tid1, NULL, thr_fun1, NULL);
if(err != 0)
{
perror("pthread_create error");
exit(1);
}
err = pthread_create(&tid2, NULL, thr_fun2, NULL);
if(err != 0)
{
perror("pthread_create error");
exit(1);
}
err = pthread_join(tid1, &ret);
if(err != 0)
{
perror("Can't join with thread 1");
exit(2);
}
printf("thread 1 exit code %ld\n", (long)ret);
err = pthread_join(tid2, &ret);
if(err != 0)
{
perror("Can't join with thread 2");
exit(2);
}
printf("thread 2 exit code %ld\n", (long)ret);
return 0;
}
void * thr_fun1(void * arg)
{
(void)arg;
printf("thread 1 returning!\n");
return ((void*)1);
}
void * thr_fun2(void * arg)
{
(void)arg;
printf("thread 2 exiting!\n");
pthread_exit((void*)2);
}
编译环境: CentOS 7
执行结果:
当一个线程调用 pthread_exit 退出或者简单的从启动例程返回时,进程中的其他进程可以通过调用 pthread_join 函数获取该线程的退出状态。
而且这个例子也看到了,线程谁先执行,是由调度器决定的。
pthread_create 和 pthread_exit 函数的无类型指针参数可以传递的参数不止一个,这个指针可以传递包含复杂信息的结构的地址,需要注意的是,这个结构所使用的内存在调用者完成调用以后必须仍然是有效的。
3.线程取消
线程可以通过调用 pthread_cancel 函数来请求取消同一进程的中的其他线程。
#include <pthread.h>
int pthread_cancel(pthread_t thread);
默认情况下,pthread_cancel 函数会使得由 thread 标识的线程的行为如同调用了参数为 PTHREAD_CANCELED 的 pthread_exit 函数,但是,线程可以选择忽略或者控制如何被取消。
- pthread_cancel 并不等待线程终止,它仅仅提出请求。
4.线程分离
默认情况下,线程的终止状态会保存直到对该进程调用 pthread_join。
如果线程已被分离,线程的底层存储资源可以在线程终止时立即被回收。
线程被分离后,不能用 pthread_join 函数等待它的终止状态,因为对分离状态的线程调用 pthread_join 会产生未定义行为。
#include <pthread.h>
int pthread_detach(pthread_t thread);
返回值:若成功,返回 0;否则,返回错误编号