目录
与进程类似,线程(thread)是允许应用程序并发执行多个任务的一种机制。一个进程可以包含多个线程。同一个程序中的所有线程均会独立执行相同程序,且共享同一份全局内存区域,其中包括初始化数据段、未初始化数据段、以及堆内存段。(传统意义上的Unix进程只是多线程程序的一个特例,该进程只会包含一个线程)
进程是CPU分配资源的最小单位,线程是操作系统调度执行的最小单位。
线程是轻量级的进程(LWP:Light Weight Process),在Linux环境下线程的本质仍是进程。
查看指定的进程的LWP号:ps -Lf pid
进程间的信息难以共享。由于除去只读代码段外,父子进程并未共享内存,因此必须采用一些进程间通信方式,在进程间进行信息交换。
调用fork()来创建进程的代价相对较高,即便存在这写时拷贝的这个技术,仍然需要复制诸如内存页表和文件描述符表之类的多种进程属性,这意味着fork()调用在时间上的开销依然不菲。
线程之间能够方便、快速地共享信息。只需将数据复制到共享(全局或堆)变量中即可。创建线程比创建进程通常要快十倍甚至更多。线程间是共享虚拟地址空间的,无需采用写时复制来复制内存,也无需复制页表。

对于进程,由于写时拷贝的技术,当创建了一个子进程的时候,他会进行写时拷贝,把上面的东西再复制一份。
但是对于线程,由于其共享内存,所以他不会复制这个表,它只会在栈空间以及代码段将其进行分区,把每个线程都在这个段中分配好自己的内存空间。
共享资源有如下:
进程ID和父进程ID
进程组ID和会话ID
用户ID和用户组ID
文件描述符表
信号处置
文件系统的相关信息:文件权限掩码(umask)、当前工作目录
虚拟地址空间(除栈、.text)
其实以上总的来说是内核的数据。
非共享资源
线程ID
信号掩码
线程特有的数据
error变量
实时调度策略和优先级
栈,本地变量和函数的调用链接信息
当Linux最初开发时,在内核中并不能真正使用线程。但是它的确可以通过clone()系统调用将进程作为可调度的实体。这个调用创建了调用进程的一个拷贝,这个拷贝与调度进程共享相同的地址空间。LinuxThreads项目使用这个调用来完全在用户空间模拟对线程的支持。不幸的是,这种方法有一些缺点,尤其是在信号处理、调度和进程间同步等方面都存在问题。另外,这个线程模型也不符合POSIX的要求。
要改进的LinuxThreads,需要内核的支持,并且重写线程库。有两个相互竞争的项目开始来满足这些要求。一个包括IBM的开发人员的团队开展了NGPT(Next-Generation POSIX Threads)项目。同时,Red Hat的一些开发人员开展了NPTL项目。NGPT在2003年中期被放弃了,把这个领域完全留给了NPTL。
NPTL,或称为Native POSIX Thread Library,是Linux线程的一个新实现,它克服了LinuxThreads的缺点,同时也复合了POSIX的需求。与LinuxThreads相比,它的性能和稳定性方面都提供了重大的改进。
可以查看自己的pthread版本:getconf GNU_LIBPTHREAD_VERSION
使用函数pthread_create(),一般情况下,main函数所在的线程我们称之为主线程(main线程),其余创建的线程称之为子线程。程序中默认只有一个进程,使用fork函数进行调用的话,会产生两个进程;程序中默认只有一个线程,pthread_create()函数调用,2个线程。
- #include
- int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
- void *(*start_routine) (void *), void *arg);
-
- - 功能:创建一个子线程
- - 参数:
- - thread:传出参数,线程创建成功后,子线程的线程ID被写到 该变量中。
- - attr : 设置线程的属性,一般使用默认值,NULL
- - start_routine : 函数指针,这个函数是子线程需要处理的逻辑代码
- - arg : 给第三个参数使用,传参
- - 返回值:
- 成功:0
- 失败:返回错误号。这个错误号和之前errno不太一样。
- 获取错误号的信息: char * strerror(int errnum);
在这个函数的说明文档中解释了,线程退出的四个前提:

那么我们在一个线程中开辟子线程:
- #include
- #include
- #include
- #include
-
- void * callback(void * arg) {
- printf("child thread...\n");
- printf("arg value: %d\n", *(int *)arg);
- return NULL;
- }
-
- int main() {
-
- pthread_t tid;
-
- int num = 10;
-
- // 创建一个子线程,并且进行传参
- int ret = pthread_create(&tid, NULL, callback, (void *)&num);
-
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error : %s\n", errstr);
- }
-
- for(int i = 0; i < 5; i++) {
- printf("%d\n", i);
- }
-
- sleep(1); //防止主线程先结束
-
- return 0; // exit(0);
- }
编译的时候需要引入第三方库:
gcc pthread_create.c -o create -lpthread
使用函数pthread_exit,在这里也学习一下其他的函数:
- #include
- void pthread_exit(void *retval);
- 功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
- 参数:
- retval:需要传递一个指针,作为一个返回值,可以在pthread_join()中获取到。
-
- pthread_t pthread_self(void);
- 功能:获取当前的线程的线程ID
-
- int pthread_equal(pthread_t t1, pthread_t t2);
- 功能:比较两个线程ID是否相等
- 不同的操作系统,pthread_t类型的实现不一样,有的是无符号的长整型,有的
- 是使用结构体去实现的,所以不是说用==就可以解决的。
看看代码:
- #include
- #include
- #include
-
- void * callback(void * arg) {
- printf("child thread id : %ld\n", pthread_self());
- return NULL; // pthread_exit(NULL);
- }
-
- int main() {
-
- // 创建一个子线程
- pthread_t tid;
- int ret = pthread_create(&tid, NULL, callback, NULL);
-
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error : %s\n", errstr);
- }
-
- // 主线程
- for(int i = 0; i < 5; i++) {
- printf("%d\n", i);
- }
-
- printf("tid : %ld, main thread id : %ld\n", tid ,pthread_self());
-
- // 让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
- pthread_exit(NULL);
- // 这个不会打印
- printf("main thread exit\n");
-
- return 0; // exit(0);
- }
首先介绍一下函数pthread_join():
在这里先补充一点,当子进程结束需要回收资源时,需要父进程来进行回收,主动的方式是,尽管父进程结束,它也会调用初始化程序来回收这个子进程,被动的方式是,使用wait或者是waitpid函数来等待子进程结束。
但是对于线程来说,任意一个线程,都可以回收要结束的线程资源,不一定需要通过父线程。所以为什么需要连接,因为连接后才可以让其资源得到释放,否则会产生僵尸线程。
- #include
- int pthread_join(pthread_t thread, void **retval);
- - 功能:和一个已经终止的线程进行连接
- 回收子线程的资源
- 这个函数是阻塞函数,调用一次只能回收一个子线程
- 一般在主线程中使用
- - 参数:
- - thread:需要回收的子线程的ID
- - retval: 接收子线程退出时的返回值,是一个二级指针,需要对底层传过来的地址进行解引用然后修改
- - 返回值:
- 0 : 成功
- 非0 : 失败,返回的错误号
看看代码:
- #include
- #include
- #include
- #include
-
- int value = 10;
-
- void * callback(void * arg) {
- printf("child thread id : %ld\n", pthread_self());
- // sleep(3);
- // return NULL;
- pthread_exit((void *)&value); // return (void *)&value; 返回这个值的地址
- }
-
- int main() {
-
- // 创建一个子线程
- pthread_t tid;
- int ret = pthread_create(&tid, NULL, callback, NULL);
-
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error : %s\n", errstr);
- }
-
- // 主线程
- for(int i = 0; i < 5; i++) {
- printf("%d\n", i);
- }
-
- printf("tid : %ld, main thread id : %ld\n", tid ,pthread_self());
-
- // 主线程调用pthread_join()回收子线程的资源
- int * thread_retval;
- ret = pthread_join(tid, (void **)&thread_retval);
-
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error : %s\n", errstr);
- }
-
- printf("exit data : %d\n", *thread_retval);
-
- printf("回收子线程资源成功!\n");
-
- // 让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
- pthread_exit(NULL);
-
- return 0;
- }
下面介绍函数:
- #include
- int pthread_detach(pthread_t thread);
- - 功能:分离一个线程。被分离的线程在终止的时候,会自动释放资源返回给系统。这样子就不需要使用join的函数来进行链接。
- 1.不能多次分离,会产生不可预料的行为。
- 2.不能去连接一个已经分离的线程,会报错。
- - 参数:需要分离的线程的ID
- - 返回值:
- 成功:0
- 失败:返回错误号
其使用如下:
- #include
- #include
- #include
- #include
-
- void * callback(void * arg) {
- printf("chid thread id : %ld\n", pthread_self());
- return NULL;
- }
-
- int main() {
-
- // 创建一个子线程
- pthread_t tid;
-
- int ret = pthread_create(&tid, NULL, callback, NULL);
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error1 : %s\n", errstr);
- }
-
- // 输出主线程和子线程的id
- printf("tid : %ld, main thread id : %ld\n", tid, pthread_self());
-
- // 设置子线程分离,子线程分离后,子线程结束时对应的资源就不需要主线程释放
- ret = pthread_detach(tid);
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error2 : %s\n", errstr);
- }
-
- // 设置分离后,对分离的子线程进行连接 pthread_join()
- // ret = pthread_join(tid, NULL);
- // if(ret != 0) {
- // char * errstr = strerror(ret);
- // printf("error3 : %s\n", errstr); //这里会打印invalid argument
- // }
-
- pthread_exit(NULL);
-
- return 0;
- }
下面看看函数pthread_cancel:
- #include
- int pthread_cancel(pthread_t thread);
- - 功能:取消线程(让线程终止)
- 取消某个线程,可以终止某个线程的运行,
- 但是并不是立马终止,而是当子线程执行到一个取消点,线程才会终止。
- 取消点:系统规定好的一些系统调用,我们可以粗略的理解为从用户区到内核区的切换,这个位置称之为取消点。(因系统而异)
关于取消点的补充:线程检查是否被取消并按照请求进行动作的一个位置。取消点也是线程检测是否被取消的一个位置。
pthreads标准制定了几个取消点,其中包括:
通过pthread_testcancel调用以编程方式建立线程取消点。
线程等待pthread_cond_wait或pthread_cond_timewait()中的特定条件。 (错误的程序设计可能会在取消时导致死锁)
被sigwait()阻塞的函数。
一些标准的库调用。通常,这些调用包括线程可基于阻塞的函数。
那么这个函数pthread_cancel到底做了什么:
线程默认是可以被取消的。
pthread_cancel函数只是给线程发送一个取消请希望可以将线程终止。
对于接收请求的线程来说,只是一种建议。
接收到的取消请求线程可能会马上停止,也可能不会直到遇到一个取消点之后。
那么这里就不扯太深了,可以看看下面的这个代码,到时候下面介绍一些概念时会实践到,下面这是一个线程取消的使用例子,运行的时候可以发现它取消线程每次运行起来都不一样:
- #include
- #include
- #include
- #include
-
- void * callback(void * arg) {
- printf("chid thread id : %ld\n", pthread_self());
- for(int i = 0; i < 5; i++) {
- printf("child : %d\n", i);
- }
- return NULL;
- }
-
- int main() {
-
- // 创建一个子线程
- pthread_t tid;
-
- int ret = pthread_create(&tid, NULL, callback, NULL);
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error1 : %s\n", errstr);
- }
-
- // 取消线程
- pthread_cancel(tid);
-
- for(int i = 0; i < 5; i++) {
- printf("%d\n", i);
- }
-
- // 输出主线程和子线程的id
- printf("tid : %ld, main thread id : %ld\n", tid, pthread_self());
-
-
- pthread_exit(NULL);
-
- return 0;
- }
对于结构体pthread_attr_t,这个结构体包含了所有的线程属性的信息。所以我们需要对这个结构体进行操作,才可以更改其进程属性,其实无非就是开辟一块内存,然后存放其相应的信息,主要涉及的函数有如下:
int pthread_attr_init(pthread_attr_t *attr);
初始化线程属性变量
int pthread_attr_destroy(pthread_attr_t *attr); - 释放线程属性的资源
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate); - 获取线程分离的状态属性
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate); - 设置线程分离的状态属性
当然还有很多函数可以被发现,具体的看名称就知道其是做什么的了:

那么这里就设置一下它的分离属性吧:
对于函数pthread_attr_setdetachstate具有三个宏值可以设置:
PTHREAD_CREATE_DETACHED:设置为分离
PTHREAD_CREATE_JOINABLE:设置为加入
需要注意的是,我们在上面创建线程时,并没有写入线程属性,每次都是使用NULL来进行配置,那么现在使用线程属性来更改,具体使用如下:
- #include
- #include
- #include
- #include
-
- void * callback(void * arg) {
- printf("chid thread id : %ld\n", pthread_self());
- return NULL;
- }
-
- int main() {
-
- // 创建一个线程属性变量
- pthread_attr_t attr;
- // 初始化属性变量
- pthread_attr_init(&attr);
-
- // 设置属性
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-
- // 创建一个子线程
- pthread_t tid;
-
- int ret = pthread_create(&tid, &attr, callback, NULL);
- if(ret != 0) {
- char * errstr = strerror(ret);
- printf("error1 : %s\n", errstr);
- }
-
- // 获取线程的栈的大小
- size_t size;
- pthread_attr_getstacksize(&attr, &size);
- printf("thread stack size : %ld\n", size);
-
- // 输出主线程和子线程的id
- printf("tid : %ld, main thread id : %ld\n", tid, pthread_self());
-
- // 释放线程属性资源
- pthread_attr_destroy(&attr);
-
- pthread_exit(NULL);
-
- return 0;
- }
多线程以及多进程的开发都是为了实现并发。那么下面可以看看使用多线程实现卖票的案例,开辟了三个线程进行票据的买卖:
- /*
- 使用多线程实现买票的案例。
- 有3个窗口,一共是100张票。
- */
- #include
- #include
- #include
-
- // 全局变量,所有的线程都共享这一份资源。
- int tickets = 100;
-
- void * sellticket(void * arg) {
- // 卖票
- while(tickets > 0) {
- usleep(6000);
- printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
- tickets--;
- }
- return NULL;
- }
-
- int main() {
-
- // 创建3个子线程
- pthread_t tid1, tid2, tid3;
- pthread_create(&tid1, NULL, sellticket, NULL);
- pthread_create(&tid2, NULL, sellticket, NULL);
- pthread_create(&tid3, NULL, sellticket, NULL);
-
- // 回收子线程的资源,阻塞
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- pthread_join(tid3, NULL);
-
- pthread_exit(NULL); // 退出主线程
-
- return 0;
- }
使用延时的时候,可以发现它一张票卖了三次,有时候还会出现卖负数门票的情况,可以发现这个三个线程一直在抢占CPU。所以这就是我们线程同步问题,关于这么处理,那么我们需要用到处理线程同步的方式,必须把这些操作设定为原子操作。
线程的主要优势在于,能够通过全局变量来共享信息。不过,这种便携的共享是有代价的;必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程修改的变量。(否则会出现数据安全现象)
临界区是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作,也就是同时访问同一共享资源的其他线程不应中断该片段的执行。
线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到线程完成操作,其他线程才能对内存地址进行操作,而其他线程则处于等待状态,肯定会影响效率,但是起码他只是影响了代码的一小部分。
为避免线程更新共享变量时出现问题,可以使用互斥量(mutex——mutual exclusion)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。
互斥量有两种状态:已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或报错失败,具体取决于加锁时使用的方法。
一旦线程锁定互斥量,随即称为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:
针对共享资源锁定互斥量。
访问共享资源。
对互斥量解锁。

如果多个线程试图执行这一块代码(一个临界区),事实上只有一个线程能够持有该互斥量(其他线程将遭到阻塞),即同时只有一个线程能够进入这段代码区域。
关于互斥量有如下的操作函数,与线程属性相似,它具有一个互斥量类型pthread_mutex_t:
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); - 初始化互斥量 - 参数 : - mutex : 需要初始化的互斥量变量 - attr : 互斥量相关的属性,NULL - restrict : C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。 pthread_mutex_t *restrict mutex = xxx; pthread_mutex_t * mutex1 = mutex;(不可以这么操作)
int pthread_mutex_destroy(pthread_mutex_t *mutex); - 释放互斥量的资源
int pthread_mutex_lock(pthread_mutex_t *mutex); - 加锁,阻塞的,如果有一个线程加锁了,那么其他的线程只能阻塞等待
int pthread_mutex_trylock(pthread_mutex_t *mutex); - 尝试加锁,如果加锁失败,不会阻塞,会直接返回。
int pthread_mutex_unlock(pthread_mutex_t *mutex); - 解锁
那么我们卖票的那个程序即可以这么修改:
- #include
- #include
- #include
-
- // 全局变量,所有的线程都共享这一份资源。
- int tickets = 1000;
-
- // 创建一个互斥量,需要为全局变量
- pthread_mutex_t mutex;
-
- void * sellticket(void * arg) {
-
- // 卖票
- while(1) {
-
- // 加锁
- pthread_mutex_lock(&mutex);
-
- if(tickets > 0) {
- usleep(6000);
- printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
- tickets--;
- }else {
- // 解锁
- pthread_mutex_unlock(&mutex);
- break;
- }
-
- // 解锁,这个线程用完则解锁
- pthread_mutex_unlock(&mutex);
- }
-
-
-
- return NULL;
- }
-
- int main() {
-
- // 初始化互斥量
- pthread_mutex_init(&mutex, NULL);
-
- // 创建3个子线程
- pthread_t tid1, tid2, tid3;
- pthread_create(&tid1, NULL, sellticket, NULL);
- pthread_create(&tid2, NULL, sellticket, NULL);
- pthread_create(&tid3, NULL, sellticket, NULL);
-
- // 回收子线程的资源,阻塞
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- pthread_join(tid3, NULL);
-
- pthread_exit(NULL); // 退出主线程
-
- // 释放互斥量资源
- pthread_mutex_destroy(&mutex);
-
- return 0;
- }
如果代码这么写的话,会使一个线程一直在运行这个东西:


问题是我们把锁加在了while的前面,线程A一直满足于这个条件并且没有解锁,所以导致了剩下的两个线程并没有去运行这个东西。
在使用互斥量的时候,会可能出现一些问题,这些问题就是叫死锁。
有时候,一个线程需要同时访问两个或更多不同的共享资源,就好比我们有两个共享资源AB,如果我们只加一个互斥量,同时锁住AB,如果AB离得近还好说,但是如果它中间隔着有一大段代码,那还是再考虑加个锁吧。所以就有了每个资源又都由不同的互斥量管理,当超过一个线程加锁同一组互斥量时,就有可能发生死锁。
两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,他们都无法推进下去,此时称系统处于死锁状态或系统产生了死锁。
死锁的几种场景:
忘记释放锁
重复加锁(一个线程加了两道锁,两个锁都是一样的锁)
多线程多锁,抢占锁资源

关于多线程多锁的情况可以看看下面的代码:
- #include
- #include
- #include
-
- // 创建2个互斥量
- pthread_mutex_t mutex1, mutex2;
-
- void * workA(void * arg) {
-
- pthread_mutex_lock(&mutex1);
- sleep(1);
- pthread_mutex_lock(&mutex2);
-
- printf("workA....\n");
-
- // 解锁顺序需要相反
- pthread_mutex_unlock(&mutex2);
- pthread_mutex_unlock(&mutex1);
- return NULL;
- }
-
-
- void * workB(void * arg) {
- //注意这里加锁的顺序与A是相反的,所以它首先拿到了另外一个锁
- pthread_mutex_lock(&mutex2);
- sleep(1);
- pthread_mutex_lock(&mutex1);
-
- printf("workB....\n");
-
- pthread_mutex_unlock(&mutex1);
- pthread_mutex_unlock(&mutex2);
-
- return NULL;
- }
-
- int main() {
-
- // 初始化互斥量
- pthread_mutex_init(&mutex1, NULL);
- pthread_mutex_init(&mutex2, NULL);
-
- // 创建2个子线程
- pthread_t tid1, tid2;
- pthread_create(&tid1, NULL, workA, NULL);
- pthread_create(&tid2, NULL, workB, NULL);
-
- // 回收子线程资源
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
-
- // 释放互斥量资源
- pthread_mutex_destroy(&mutex1);
- pthread_mutex_destroy(&mutex2);
-
- return 0;
- }
转载于小林Coding。
当两个线程为了保护两个不同的共享资源而使用了两个互斥锁,那么这两个互斥锁应用不当的时候,可能会造成两个线程都在等待对方释放锁,在没有外力的作用下,这些线程会一直相互等待,就没办法继续运行,这种情况就是发生了死锁,那么死锁只有同时满足以下四个条件才会发生:
互斥条件。
持有并等待条件。
不可剥夺条件。
环路等待条件。
互斥条件:对于互斥条件是指多个线程不能同时同一个资源:如果线程 A 已经持有的资源,不能再同时被线程 B 持有,如果线程 B 请求获取线程 A 已经占用的资源,那线程 B 只能等待,直到线程 A 释放了资源。

持有并等待条件:持有并等待条件是指,当线程 A 已经持有了资源 1,又想申请资源 2,而资源 2 已经被线程 C 持有了,所以线程 A 就会处于等待状态,但是线程 A 在等待资源 2 的同时并不会释放自己已经持有的资源 1。

不可剥夺条件:不可剥夺条件是指,当线程已经持有了资源 ,在自己使用完之前不能被其他线程获取,线程 B 如果也想使用此资源,则只能在线程 A 使用完并释放后才能获取。

环路等待条件:环路等待条件指的是,在死锁发生的时候,两个线程获取资源的顺序构成了环形链。
比如,线程 A 已经持有资源 2,而想请求资源 1, 线程 B 已经获取了资源 1,而想请求资源 2,这就形成资源请求等待的环形图。也就是上述那个代码的情况。

那么避免死锁的问题就需要破坏其中一个条件即可,那么最常见的方法且可行的就是使用资源有序分配法,来破坏环路等待条件。
线程 A 和 线程 B 获取资源的顺序要一样,当线程 A 是先尝试获取资源 A,然后尝试获取资源 B 的时候,线程 B 同样也是先尝试获取资源 A,然后尝试获取资源 B。也就是说,线程 A 和 线程 B 总是以相同的顺序申请自己想要的资源。这样就可以打破死锁了:

当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其他几个线程也想读取这个共享资源,但是由于互斥锁的排他性,所有其他线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。
在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用。为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。
读写锁的特点:
如果有其他线程读数据,则允许其他线程执行读操作,但不允许写操作。
如果有其他线程写数据,则其他线程都不允许读、写操作。
写是独占的,写的优先级高。
那么关于读写锁相关的操作函数,有如下,当然,这里也有一个结构体,表达了读写锁的属性pthread_rwlock_t,这里也是一把锁,只不过是可以设置为读或者是写:
初始化:int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr); 销毁:int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); 读操作:int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); 尝试读操作:int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock); 写操作:int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); 尝试写操作:int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock); 解锁:int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
那么下面我们写个代码,实现的是开启八个线程,在八个线程中操作同一个全局变量,3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量:
- #include
- #include
- #include
-
- // 创建一个共享数据
- int num = 1;
- // pthread_mutex_t mutex;
- pthread_rwlock_t rwlock;
-
- void * writeNum(void * arg) {
-
- while(1) {
- pthread_rwlock_wrlock(&rwlock);
- num++;
- printf("++write, tid : %ld, num : %d\n", pthread_self(), num);
- pthread_rwlock_unlock(&rwlock);
- usleep(100);
- }
-
- return NULL;
- }
-
- void * readNum(void * arg) {
-
- while(1) {
- pthread_rwlock_rdlock(&rwlock);
- printf("===read, tid : %ld, num : %d\n", pthread_self(), num);
- pthread_rwlock_unlock(&rwlock);
- usleep(100);
- }
-
- return NULL;
- }
-
- int main() {
-
- pthread_rwlock_init(&rwlock, NULL);
-
- // 创建3个写线程,5个读线程
- pthread_t wtids[3], rtids[5];
- for(int i = 0; i < 3; i++) {
- pthread_create(&wtids[i], NULL, writeNum, NULL);
- }
-
- for(int i = 0; i < 5; i++) {
- pthread_create(&rtids[i], NULL, readNum, NULL);
- }
-
- // 设置线程分离
- for(int i = 0; i < 3; i++) {
- pthread_detach(wtids[i]);
- }
-
- for(int i = 0; i < 5; i++) {
- pthread_detach(rtids[i]);
- }
-
- pthread_exit(NULL);
-
- pthread_rwlock_destroy(&rwlock);
-
- return 0;
- }
这里需要防止的是重复读以及重复写,而且读写的输出也需要同步,所以需要引出读写锁,当然使用互斥锁是可以解决的,但是缺点就是在于它没办法同时去读取。
假设有两个进程(或线程)A、B和一个固定大小的缓冲区,A进程产生的数据放入缓冲区,B进程从缓冲区中取出数据进行计算,这就是一个简单的生产者和消费者模型。这里的A相当于生产者,B相当于消费者:

这个模型所需要的对象有:
生产者
消费者
容器
在多线程开发中,如果生产者生产数据的速度很快,而消费者消费数据的速度很慢,那么生产者就必须等待消费者消费完数据才能够继续生产数据,因为生产过多的数据可能会导致存储不足;同理如果消费者的速度大于生产者那么消费者就会经常处理等待状态,所以为了达到生产者和消费者生产数据和消费数据之间的平衡,那么就需要一个缓冲区用来存储生产者生产的数据,所以就引入了这个模式。
简单来说,这里缓冲区的作用就是为了平衡生产者和消费者的数据处理能力,一方面起到缓存作用,另一方面达到解耦合作用。那么如何去解决这个问题,需要使用条件变量和信号量来解决这个问题。
保证生产者不会在缓冲区满的时候继续向缓冲区中放入数据,而消费者也不会在缓冲区空的时候消耗数据。
当缓冲区满时,生产者会进入休眠状态,当下次消费者开始消耗缓冲区的数据时,生产者才会被唤醒,开始往缓冲区中添加数据;当缓冲区空时,消费者也会进入休眠状态,直到生产者往缓冲区中添加数据时才会被唤醒。
条件变量不是锁,但是它可以引起线程阻塞,满足条件后解除阻塞,它是配合互斥量来实现的,当然它也有一个结构体pthread_cond_t,其操作的代码有如下:
初始化:int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); 销毁:int pthread_cond_destroy(pthread_cond_t *cond); 等待(发现没有数据等等):int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex); 等待多长时间:int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime); 发送信号(唤醒部分):int pthread_cond_signal(pthread_cond_t *cond); 广播(唤醒所有):int pthread_cond_broadcast(pthread_cond_t *cond);
其实这个条件变量的加入,主要是为了防止不断地花时间去判断是否有没有变化,这是与平时编程不一样的一点。
信号量这个东西也是用于阻塞线程的,相当于是在亮灯,他只能告诉线程当前数据是否可读可写,但是它并不能真正的保证数据的安全问题,所以也需要配合互斥锁的使用,当然也有一个结构体sem_t,其操作的代码有如下:
- 信号量的类型 sem_t
- int sem_init(sem_t *sem, int pshared, unsigned int value);
- - 初始化信号量
- - 参数:
- - sem : 信号量变量的地址
- - pshared : 0 用在线程间 ,非0 用在进程间
- - value : 信号量中的值
-
- int sem_destroy(sem_t *sem);
- - 释放资源
-
- int sem_wait(sem_t *sem);
- - 对信号量加锁,调用一次对信号量的值-1,如果值为0,就阻塞
-
- int sem_trywait(sem_t *sem);
-
- int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
- int sem_post(sem_t *sem);
- - 对信号量解锁,调用一次对信号量的值+1
-
- int sem_getvalue(sem_t *sem, int *sval);
- - 获取信号量的值
-
- 下面是一个实现生产者消费者的伪代码:
- sem_t psem;
- sem_t csem;
- init(psem, 0, 8);
- init(csem, 0, 0);
-
- producer() {
- sem_wait(&psem);
- sem_post(&csem)
- }
-
- customer() {
- sem_wait(&csem);
- sem_post(&psem)
- }
(一)使用条件变量实现
对于这个模型,需要声明一个链表的结构来完成这个模型,并且需要开辟多个线程来满足生产者以及消费者的条件,对于要解决数据安全的问题,那我们要加入互斥量、信号量、条件变量等:
需要保证有缓存才去消费(创建互斥量并且加入判断)。
不要一直在判断,提高这个模型的性能。(使用条件变量)
- #include
- #include
- #include
- #include
-
- // 创建一个互斥量
- pthread_mutex_t mutex;
- // 创建条件变量
- pthread_cond_t cond;
-
- struct Node{
- int num;
- struct Node *next;
- };
-
- // 头结点
- struct Node * head = NULL;
-
- void * producer(void * arg) {
-
- // 不断的创建新的节点,添加到链表中
- while(1) {
- pthread_mutex_lock(&mutex);
- struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
- newNode->next = head;
- head = newNode;
- newNode->num = rand() % 1000;
- printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
-
- // 只要生产了一个,就通知消费者消费
- pthread_cond_signal(&cond);
-
- pthread_mutex_unlock(&mutex);
- usleep(100);
- }
-
- return NULL;
- }
-
- void * customer(void * arg) {
-
- while(1) {
- pthread_mutex_lock(&mutex);
- // 保存头结点的指针
- struct Node * tmp = head;
- // 判断是否有数据
- if(head != NULL) {
- // 有数据
- head = head->next;
- printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
- free(tmp);
- pthread_mutex_unlock(&mutex);
- usleep(100);
- } else {
- // 没有数据,需要等待
- // 当这个函数调用阻塞的时候,会对互斥锁进行解锁,当不阻塞的,继续向下执行,会重新加锁。
- pthread_cond_wait(&cond, &mutex);
- pthread_mutex_unlock(&mutex);
- }
- }
- return NULL;
- }
-
- int main() {
-
- pthread_mutex_init(&mutex, NULL);
- pthread_cond_init(&cond, NULL);
-
- // 创建5个生产者线程,和5个消费者线程
- pthread_t ptids[5], ctids[5];
-
- for(int i = 0; i < 5; i++) {
- pthread_create(&ptids[i], NULL, producer, NULL);
- pthread_create(&ctids[i], NULL, customer, NULL);
- }
-
- for(int i = 0; i < 5; i++) {
- pthread_detach(ptids[i]);
- pthread_detach(ctids[i]);
- }
-
- // 防止互斥量被销毁
- while(1) {
- sleep(10);
- }
-
- pthread_mutex_destroy(&mutex);
- pthread_cond_destroy(&cond);
-
- pthread_exit(NULL);
-
- return 0;
- }
(二)使用信号量实现
- #include
- #include
- #include
- #include
- #include
-
- // 创建一个互斥量
- pthread_mutex_t mutex;
- // 创建两个信号量
- sem_t psem;
- sem_t csem;
-
- struct Node{
- int num;
- struct Node *next;
- };
-
- // 头结点
- struct Node * head = NULL;
-
- void * producer(void * arg) {
-
- // 不断的创建新的节点,添加到链表中
- while(1) {
- sem_wait(&psem); //可以生产八个
- pthread_mutex_lock(&mutex);
- struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
- newNode->next = head;
- head = newNode;
- newNode->num = rand() % 1000;
- printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
- pthread_mutex_unlock(&mutex);
- sem_post(&csem); //告诉消费者可以消费
- }
-
- return NULL;
- }
-
- void * customer(void * arg) {
-
- while(1) {
- sem_wait(&csem); //等待生产者生产数据
- pthread_mutex_lock(&mutex);
- // 保存头结点的指针
- struct Node * tmp = head;
- head = head->next;
- printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
- free(tmp);
- pthread_mutex_unlock(&mutex);
- sem_post(&psem); //告知生产者已经消耗
-
- }
- return NULL;
- }
-
- int main() {
-
- pthread_mutex_init(&mutex, NULL);
- sem_init(&psem, 0, 8);
- sem_init(&csem, 0, 0);
-
- // 创建5个生产者线程,和5个消费者线程
- pthread_t ptids[5], ctids[5];
-
- for(int i = 0; i < 5; i++) {
- pthread_create(&ptids[i], NULL, producer, NULL);
- pthread_create(&ctids[i], NULL, customer, NULL);
- }
-
- for(int i = 0; i < 5; i++) {
- pthread_detach(ptids[i]);
- pthread_detach(ctids[i]);
- }
-
- while(1) {
- sleep(10);
- }
-
- pthread_mutex_destroy(&mutex);
-
- pthread_exit(NULL);
-
- return 0;
- }