文章目录
第3章 Linux多线程开发
3.1 线程概述
- 与进程(process)类似,线程 (thread) 是允许应用程序并发执行多个任务的一种机与进程制。一个进程可以包含多个线程。同一个程序中的所有线程均会独立执行相同程序,且共享同一份全局内存区域,其中包括初始化数据段、未初始化数据段,以及堆内存段。(传统意义上的 UNIX 进程只是多线程程序的一个特例,该进程只包含一个线程)
- 进程是 CPU 分配资源的最小单位,线程是操作系统调度执行的最小单位。
- 线程是轻量级的进程(LWP:Light weight Process),在 Linux 环境下线程的本质仍是进程。
- 查看指定进程的 LWP 号: ps -Lf pid
3.1.1 线程和进程的区别
- 进程间的信息难以共享。由于除去只读代码段外,父子进程并未共享内存,因此必须采用些进程间通信方式,在进程间进行信息交换
- 调用 fork()来创建进程的代价相对较高,即便利用写时复制技术,仍热需要复制诸如内存页表和文件描述符表之类的多种进程属性,这意味着 fork() 调用在时间上的开销依然不菲。
- 线程之间能够方便、快速地共享信息。只需将数据复制到共享 (全局或堆)变量中即可
- 创建线程比创建进程通常要快 10 倍甚至更多。线程间是共享虚拟地址空间的,无需采用写时复制来复制内存,也无需复制页表。
创建线程还是共享原来的虚拟地址空间(使用原来的,不是重新开辟空间),只不过会把栈空间,.text分为很多的空间,分配给每一个线程。
3.1.2 线程之间共享和非共享资源
共享资源
- 进程 ID 和父进程 ID
- 进程组 ID 和会话 ID
- 用户 ID 和用户组 ID
- 文件描述符表
- 信号处置
- 文件系统的相关信息:文件权限掩码(umask)、当前工作目录
- 虚拟地址空间 (除栈、.text)
非共享资源
- 线程ID
- 信号掩码
- 线程特有数据
- error 变量
- 实时调度策略和优先级
- 栈,本地变量和函数的调用链接信息
3.1.3 NPTL
- 当 Linux 最初开发时,在内核中并不能真正支持线程。但是它的确可以通过 clone()系统调用将进程作为可调度的实体。这个调用创建了调用进程 (calling process)的个拷贝,这个拷贝与调用进程共享相同的地址空间。LinuxThreads 项目使用这个调用来完全在用户空间模拟对线程的支持。不幸的是,这种方法有一些缺点,尤其是在信号处理、调度和进程间同步等方面都存在问题。另外,这个线程模型也不符合 POSIX 的要求
- 要改进 LinuxThreads,需要内核的支持,并且重写线程库。有两个相互竞争的项目开始来满足这些要求。一个包括 IBM 的开发人员的团队开展了 NGPT (Next-GenerationPOSIX Threads)项目。同时,Red Hat 的一些开发人员开展了 NPTL 项目。NGPT在 2003年中期被放弃了,把这个领域完全留给了 NPTL。
- NPTL,或称为 Native POSIX Thread Lbrary,是 Linux 线程的一个新实现,它克服了 LinuxThreads 的缺点,同时也符合 POSIX 的需求。与 LinuxThreads 相比,它在性能和稳定性方面都提供了重大的改进。
- 查看当前 pthread 库版本:getconf GNU_LIBPTHREAD_VERSION
3.2 创建线程
3.2.1 线程操作函数
pthread_t pthread_self(void);
int pthread_equal(pthread_t t1, pthread_t t2);
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
void pthread_exit(void *retval);
int pthread_join(pthread_t thread, void **retval);
int pthread_detach(pthread_t thread);
int pthread_cancel(pthread_t thread);
ernest-laptop@ubuntu:~/Linux/lesson28$ man pthread [按下table键]
pthread_attr_destroy pthread_attr_setinheritsched pthread_exit pthread_mutexattr_setrobust pthread_setschedprio
pthread_attr_getaffinity_np pthread_attr_setschedparam pthread_getaffinity_np pthread_mutexattr_setrobust_np pthread_sigmask
pthread_attr_getdetachstate pthread_attr_setschedpolicy pthread_getattr_default_np pthread_mutex_consistent pthread_sigqueue
pthread_attr_getguardsize pthread_attr_setscope pthread_getattr_np pthread_mutex_consistent_np pthread_spin_destroy
pthread_attr_getinheritsched pthread_attr_setstack pthread_getconcurrency pthread_rwlockattr_getkind_np pthread_spin_init
pthread_attr_getschedparam pthread_attr_setstackaddr pthread_getcpuclockid pthread_rwlockattr_setkind_np pthread_spin_lock
pthread_attr_getschedpolicy pthread_attr_setstacksize pthread_getname_np pthreads pthread_spin_trylock
pthread_attr_getscope pthread_cancel pthread_getschedparam pthread_self pthread_spin_unlock
pthread_attr_getstack pthread_cleanup_pop pthread_join pthread_setaffinity_np pthread_testcancel
pthread_attr_getstackaddr pthread_cleanup_pop_restore_np pthread_kill pthread_setattr_default_np pthread_timedjoin_np
pthread_attr_getstacksize pthread_cleanup_push pthread_kill_other_threads_np pthread_setcancelstate pthread_tryjoin_np
pthread_attr_init pthread_cleanup_push_defer_np pthread_mutexattr_getpshared pthread_setcanceltype pthread_yield
pthread_attr_setaffinity_np pthread_create pthread_mutexattr_getrobust pthread_setconcurrency
pthread_attr_setdetachstate pthread_detach pthread_mutexattr_getrobust_np pthread_setname_np
pthread_attr_setguardsize pthread_equal pthread_mutexattr_setpshared pthread_setschedparam
/*
一般情况下,main函数所在的线程我们称之为主线程(main线程),其余创建的线程
称之为子线程。
程序中默认只有一个进程,fork()函数调用,2进程
程序中默认只有一个线程,pthread_create()函数调用,2个线程。
#include <pthread.h>
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 <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *callBack(void *arg)
{
printf("child thread...\n");
printf("ard 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;
}
# 编译的时候要加上: -lpthread (pthread库)
ernest-laptop@ubuntu:~/Linux/lesson29$ gcc pthread_create.c -o pthread_create -lpthread
ernest-laptop@ubuntu:~/Linux/lesson29$ ./pthread_create
0
1
2
3
4
child thread...
ard value : 10
3.3 终止线程
/*
#include <pthread.h>
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 <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
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);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson29$ gcc pthread_exit.c -o pthread_exit -lpthread
ernest-laptop@ubuntu:~/Linux/lesson29$ ./pthread_exit
0
1
2
3
4
tid : 140044597405440 , main thread id : 140044597409600
child thread id : 140044597405440
3.4 连接已终止的线程
/*
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
- 功能:和一个已经终止的线程进行连接
回收子线程的资源
这个函数是阻塞函数,调用一次只能回收一个子线程
一般在主线程中使用
- 参数:
- thread:需要回收的子线程的ID
- retval: 接收子线程退出时的返回值
- 返回值:
0 : 成功
非0 : 失败,返回的错误号
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *callBack(void *arg)
{
printf("child thread id : %ld\n", pthread_self());
// sleep(1);
int value = 10;
pthread_exit((void *)&value);
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_join()回收子线程的资源
int thread_retval;
ret = pthread_join(tid, (void **)&thread_retval); // 为什么是void(**),因为想要操作一级指针,就要用二级指针来操作
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;
}
ernest-laptop@ubuntu:~/Linux/lesson29$ gcc pthread_join.c -o pthread_join -lpthread
ernest-laptop@ubuntu:~/Linux/lesson29$ ./pthread_join
0
1
2
3
4
tid : 140681738065664 , main thread id : 140681738069824
child thread id : 140681738065664
exit data : 84283108
回收子线程资源成功!
3.5 线程的分离
/*
#include <pthread.h>
int pthread_detach(pthread_t thread);
- 功能:分离一个线程。被分离的线程在终止的时候,会自动释放资源返回给系统。
1.不能多次分离,会产生不可预料的行为。
2.不能去连接一个已经分离的线程,会报错。
- 参数:需要分离的线程的ID
- 返回值:
成功:0
失败:返回错误号
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *callBack(void *arg)
{
printf("child 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("error : %s\n", errstr);
}
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);
}
// // 设置分离后,对分离的子线程进行连接
// ret = pthread_join(tid, NULL);
// if (ret != 0)
// {
// char *errstr = strerror(ret);
// printf("error3 : %s\n", errstr);
// }
// 让主线程退出,当主线程退出时,不会影响其他正常运行的线程
pthread_exit(NULL);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson29$ ./pthread_detach
tid : 140661987563264 , main thread id : 140661987567424
child thread id : 140661987563264
3.6 线程取消
/*
#include <pthread.h>
int pthread_cancel(pthread_t thread);
- 功能:取消线程(让线程终止)
取消某个线程,可以终止某个线程的运行,
但是并不是立马终止,而是当子线程执行到一个取消点,线程才会终止。
取消点:系统规定好的一些系统调用,我们可以粗略的理解为从用户区到内核区的切换,这个位置称之为取消点。
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *callBack(void *arg)
{
printf("child 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("error : %s\n", errstr);
}
// 设置取消子线程
pthread_cancel(tid);
for (int i = 0; i < 5; i++)
{
printf("child : %d\n", i);
}
printf("tid : %ld , main thread id : %ld\n", tid, pthread_self());
pthread_exit(NULL);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson29$ gcc pthread_cancel.c -o pthread_cancel -lpthread
ernest-laptop@ubuntu:~/Linux/lesson29$ ./pthread_cancel
child thread id : 140629503575808
child : 0
child : 1
child : 2
child : 3
child : 4
child : 0
child : 1
child : 2
child : 3
child : 4
tid : 140629503575808 , main thread id : 140629503579968
3.7 线程属性
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);
- 作用:设置线程分离的状态属性
ernest-laptop@ubuntu:~/Linux/lesson29$ man pthread_attr # [按两次tab键显示与属性相关的函数]
pthread_attr_destroy pthread_attr_getinheritsched pthread_attr_getstack pthread_attr_setaffinity_np pthread_attr_setschedparam pthread_attr_setstackaddr
pthread_attr_getaffinity_np pthread_attr_getschedparam pthread_attr_getstackaddr pthread_attr_setdetachstate pthread_attr_setschedpolicy pthread_attr_setstacksize
pthread_attr_getdetachstate pthread_attr_getschedpolicy pthread_attr_getstacksize pthread_attr_setguardsize pthread_attr_setscope
pthread_attr_getguardsize pthread_attr_getscope pthread_attr_init pthread_attr_setinheritsched pthread_attr_setstack
/*
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);
- 作用:设置线程分离的状态属性
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void *callBack(void *arg)
{
printf("child 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, NULL, callBack, NULL);
if (ret != 0)
{
char *errstr = strerror(ret);
printf("error : %s\n", errstr);
}
// 获取线程属性的大小
size_t size;
pthread_attr_getstacksize(&attr, &size);
printf("size : %ld\n", size);
printf("tid : %ld , main thread id : %ld\n", tid, pthread_self());
// 让主线程退出,当主线程退出时,不会影响其他正常运行的线程
pthread_exit(NULL);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson29$ gcc pthread_attr.c -o pthread_attr -lpthread
ernest-laptop@ubuntu:~/Linux/lesson29$ ./pthread_attr
size : 8388608
tid : 140403611555584 , main thread id : 140403611559744
child thread id : 140403611555584
3.8 线程同步
- 线程的主要优势在于,能够通过全局变量来共享信息不过,这种便捷的共享是有代价的:必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程修改的变量。
- 临界区是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作,也就是司时访问同一共享资源的其他线程不应终端该片段的执行。
- 线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处于等待状态。
/*
使用多线程实现卖票的案例。
有3个窗口,一共是100张票
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int tickets = 100;
void *sellticket(void *arg)
{
while (tickets > 0)
{
usleep(6000);
printf("%ld 卖了第 %d 张票\n", pthread_self(), tickets);
tickets--;
}
}
int main()
{
// 创建3个线程
pthread_t tid, tid1, tid2;
pthread_create(&tid, NULL, sellticket, NULL);
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
// 回收子线程的资源,这个函数是阻塞的
pthread_join(tid, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
// 退出主线程
pthread_exit(NULL);
return 0;
}
rnest-laptop@ubuntu:~/Linux/lesson30$ gcc sellticket.c -o sellticket -lpthread
ernest-laptop@ubuntu:~/Linux/lesson30$ ./sellticket
140708926072576 卖了第 100 张票
140708909287168 卖了第 100 张票
140708917679872 卖了第 99 张票
140708926072576 卖了第 97 张票
140708909287168 卖了第 96 张票
...
140708909287168 卖了第 5 张票
140708926072576 卖了第 4 张票
140708917679872 卖了第 3 张票
140708909287168 卖了第 2 张票
140708926072576 卖了第 1 张票
140708917679872 卖了第 0 张票
140708909287168 卖了第 -1 张票
上面的程序涉及到线程同步的问题,输出结果不正确,下面会介绍并解决。
3.9 互斥锁
3.9.1 互斥量
- 为避免线程更新共享变量时出现问题,可以使用互斥量 (mutex 是 mutual exclusion的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。
- 互斥量有两种状态:已锁定 (locked) 和未锁定 (unlocked) 。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报错失败,具体取决于加锁时使用的方法。
- 一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:
- 针对共享资源锁定互斥量
- 访问共享资源
- 对互斥量解锁
- 如果多个线程试图执行这一块代码 (一个临界区),事实上只有一个线程能够持有该互斥量(其他线程将遭到阻塞),即同时只有一个线程能够进入这段代码区域,如下图所示
3.9.2 互斥量相关操作函数
// 互斥量的类型 pthread_mutex_t
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
- 初始化互斥量
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);
- 解锁
/*
互斥量的类型 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);
- 加锁,阻塞的,如果有一个线程加锁了,那么其他的线程只能阻塞等待
- 返回值
- 成功:返回0
- 失败:设置错误号
int pthread_mutex_trylock(pthread_mutex_t *mutex);
- 尝试加锁,如果加锁失败,不会阻塞,会直接返回。
- 返回值
- 成功:返回0
- 失败:设置错误
int pthread_mutex_unlock(pthread_mutex_t *mutex);
- 解锁
- 返回值
- 成功:返回0
- 失败:设置错误
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局变量
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);
}
}
int main()
{
// 初始化互斥量
pthread_mutex_init(&mutex, NULL);
// 创建3个线程
pthread_t tid, tid1, tid2;
pthread_create(&tid, NULL, sellticket, NULL);
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
// 回收子线程的资源,这个函数是阻塞的
pthread_join(tid, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
// 释放互斥量资源
pthread_mutex_destroy(&mutex);
// 退出主线程
pthread_exit(NULL);
return 0;
}
# 因为电脑性能的原因,每次执行的结果都会不一样,有时候只有一个线程在卖票,有时候只有两个线程,执行的次数多了才会有三个线程
ernest-laptop@ubuntu:~/Linux/lesson30$ ./mutex
140516586137344 卖了第 100 张票
...
140516594530048 卖了第 75 张票
...
140516594530048 卖了第 1 张票
3.10 死锁
- 有时,一个线程需要同时访问两个或更多不同的共享资源,而每个资源又都由不同的互斥量管理。当超过一个线程加锁同一组互斥量时,就有可能发生死锁。
- 两个或两个以上的进程在执行过程中,因争夺共享资源而造成的一种互相等待的现象若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁
- 死锁的几种场景:
- 忘记释放锁
- 重复加锁(重复加相同的锁)
- 多线程多锁,抢占锁资源(如下图,A给资源1上锁之后,需要用到资源2,然后B给资源2上了锁,B此时也要用到资源1,所以A、B互相等待,造成了死锁)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 创建两个互斥量
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);
}
void *workB(void *arg)
{
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex1);
printf("workB...\n");
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
int main()
{
// 初始化互斥量
pthread_mutex_init(&mutex1, NULL);
pthread_mutex_init(&mutex2, NULL);
// 创建两个线程
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;
}
# 发生了死锁(多线程多锁,抢占锁资源)
ernest-laptop@ubuntu:~/Linux/lesson30$ gcc deadlock.c -o deadlock -lpthread
ernest-laptop@ubuntu:~/Linux/lesson30$ ./deadlock
3.11 读写锁
- 当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其它几个线程也想读取这个共享资源,但是由于瓦斥锁的排它性,所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题
- 在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现
- 读写锁的特点:
- 如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作
- 如果有其它线程写数据,则其它线程都不允许读、写操作。
- 写是独占的,写的优先级高。
3.11.1 读写锁相关操作函数
读写锁的类型 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);
/*
读写锁的类型 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);
案例:8个线程操作同一个全局变量。
3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 创建一个共享数据
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;
}
ernest-laptop@ubuntu:~/Linux/lesson30$ gcc rwlock.c -o rwlock -lpthread
ernest-laptop@ubuntu:~/Linux/lesson30$ ./rwlock
...
===read, tid : 139829721745152, num : 1105
++write, tid : 139829730137856, num : 1106
++write, tid : 139829738530560, num : 1107
===read, tid : 139829606070016, num : 1107
===read, tid : 139829622855424, num : 1107
++write, tid : 139829639640832, num : 1108
===read, tid : 139829606070016, num : 1108
...
++write, tid : 139829738530560, num : 1119
++write, tid : 139829639640832, num : 1120
++write, tid : 139829730137856, num : 1121
===read, tid : 139829606070016, num : 1121
...
3.12 生产者和消费者模型
head = newnode和head->next = newnode有区别吗?
是的,head = newnode
和 head->next = newnode
是有区别的。
-
head = newnode
: 这将会把newnode
设置为链表的新头结点。也就是说,head
指针会指向newnode
,而newnode->next
会指向原来的链表的头结点(即原来的第一个节点)。这样就在链表的头部插入了一个新的节点,它成为了新的第一个节点,而原来的链表保持不变。 -
head->next = newnode
: 这将会把链表的头结点的next
指针指向newnode
。这实际上是在链表的头结点之后插入了一个新的节点,原来的头结点仍然保持不变,只是新的节点插入到了头结点后面。
在头插法创建单链表时,我们通常使用 head = newnode
的方式,因为我们希望新的节点成为新的头结点,而原来的链表会成为新节点的后继部分。这样做可以在O(1)时间内插入节点,因为不需要遍历整个链表来找到插入位置。
/*
生产者消费者模型(粗略版本)
*/
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
// 创建链表结构体
struct Node
{
int num;
struct Node *next;
};
struct Node *head = NULL;
void *producer(void *arg)
{
while (1)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->next = head;
head = newNode;
newNode->num = rand() % 1000;
printf("add num : %d, tid : %ld\n", newNode->num, pthread_self());
usleep(100);
}
return NULL;
}
void *customer(void *arg)
{
while (1)
{
struct Node *tmp = (struct Node *)malloc(sizeof(struct Node));
tmp = head;
head = head->next;
printf("del num : %d, tid : %ld\n", tmp->num, pthread_self());
free(tmp);
usleep(100);
}
return NULL;
}
int main()
{
// 创建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]);
}
pthread_exit(NULL);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson30$ gcc prodcust.c -o prodcust -lpthread
ernest-laptop@ubuntu:~/Linux/lesson30$ ./prodcust
add num : 383, tid : 140680081422080
......
add num : 324, tid : 140680081422080
del num : 324, tid : 140680073029376
Segmentation fault
3.13 条件变量
在Linux编程中pthread_cond_t条件变量的作用是什么?
在Linux编程中,pthread_cond_t
条件变量是一种线程同步机制,用于在多线程程序中实现线程之间的协调和通信。条件变量允许一个线程等待某个特定条件的发生,而不需要忙等待(busy-waiting),从而有效地节省了系统资源。
条件变量的主要作用是允许一个或多个线程在某个特定条件满足之前等待,同时允许其他线程在条件满足时通知等待的线程。这种通信和同步的方式有助于避免竞争条件(race conditions)和死锁(deadlocks),从而提高多线程程序的可靠性和性能。
pthread_cond_t
的主要操作函数包括:
-
pthread_cond_init
:用于初始化条件变量。 -
pthread_cond_destroy
:用于销毁条件变量。 -
pthread_cond_wait
:用于等待条件满足。在调用这个函数时,线程会阻塞并等待另一个线程调用pthread_cond_signal
或pthread_cond_broadcast
来唤醒它。 -
pthread_cond_signal
:用于唤醒一个等待在条件变量上的线程。如果有多个线程在等待,只会唤醒其中一个。 -
pthread_cond_broadcast
:用于唤醒所有等待在条件变量上的线程。
使用条件变量的典型场景包括:
-
生产者-消费者模型: 多个生产者线程和消费者线程共享一个缓冲区。当缓冲区满时,生产者需要等待条件变量,而当缓冲区为空时,消费者需要等待条件变量。生产者生产数据后,通过
pthread_cond_signal
或pthread_cond_broadcast
唤醒消费者线程。 -
线程池: 线程池中的线程在执行完任务后等待新任务的到来。当新任务到达时,使用条件变量通知空闲的线程。
-
资源分配: 多个线程竞争有限资源,例如连接池中的连接。当一个连接可用时,通过条件变量通知等待的线程可以使用这个连接。
总之,pthread_cond_t
条件变量在多线程编程中起到了重要的作用,允许线程在某个特定条件满足之前等待,从而实现线程之间的协调和通信,避免了忙等待,提高了程序的性能和可靠性。
// 条件变量的类型 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);
- 唤醒所有的等待的线程
/*
生产者消费者模型(粗略版本)
*/
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
// 创建链表结构体
struct Node
{
int num;
struct Node *next;
};
struct Node *head = NULL;
// 创建互斥量
pthread_mutex_t mutex;
// 创建条件变量
pthread_cond_t cond;
// 生产者
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 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 = (struct Node *)malloc(sizeof(struct Node));
tmp = head;
// 判断是否有数据
if (head != NULL)
{
// 有数据
head = head->next;
printf("del 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(100);
}
// 销毁互斥量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson30$ gcc prodcust.c -o prodcust lpthread
ernest-laptop@ubuntu:~/Linux/lesson30$ ./prodcust
...
add num : 72, tid : 140640210167552
...
add num : 494, tid : 140640193382144
del num : 494, tid : 140640235345664
...
3.14 信号量
在Linux编程中sem_t信号量的作用是什么?
在Linux编程中,sem_t
信号量是一种线程同步机制,用于在多线程程序中实现对共享资源的互斥访问和线程之间的协调。信号量允许控制多个线程之间的资源访问顺序,避免竞争条件(race conditions)和其他同步问题。
sem_t
信号量的主要作用是:
-
互斥访问共享资源: 信号量可以用于实现对共享资源的互斥访问,以确保在任意时刻只有一个线程可以访问这些资源。这对于避免数据的不一致性和意外修改非常重要。
-
线程间同步: 信号量可以用于在多个线程之间实现同步操作。通过在某个线程执行完一段关键代码后释放信号量,其他等待的线程可以获得信号量从而执行自己的任务。
sem_t
的主要操作函数包括:
-
sem_init
:用于初始化信号量。 -
sem_destroy
:用于销毁信号量。 -
sem_wait
:用于等待信号量的值变为非零。如果信号量的值为零,则线程会被阻塞,直到信号量的值大于零。 -
sem_post
:用于增加信号量的值,通常在临界区代码结束后调用。这会使等待在信号量上的线程被唤醒。
使用信号量的典型场景包括:
-
资源池管理: 多个线程需要共享有限数量的资源,如线程池中的线程或连接池中的连接。通过信号量,可以控制资源的可用性,避免资源过度分配。
-
生产者-消费者模型: 多个生产者线程和消费者线程共享一个缓冲区。通过信号量,可以控制缓冲区中数据的生产和消费,确保缓冲区不会溢出或为空。
-
防止竞态条件: 通过在临界区代码前后使用信号量进行加锁和解锁,可以避免多个线程同时访问临界区,从而防止竞态条件。
-
线程同步: 当某个线程需要等待其他线程完成某些任务后再继续执行,可以使用信号量来实现等待和唤醒的操作。
总之,sem_t
信号量在Linux编程中是一种重要的线程同步机制,用于管理共享资源的互斥访问和线程之间的同步,以提高程序的可靠性和性能。
信号量和条件变量
信号量(semaphore)和条件变量(condition variable)都是用于多线程编程和同步的工具,但它们有不同的用途和工作原理,没有直接的关系。下面我会解释它们的概念和用途:
-
信号量(Semaphore):
- 信号量是一种计数器,用于控制多个线程对共享资源的访问。
- 信号量可以有一个整数值,通常用于表示某个资源的可用数量。
- 信号量提供了两个主要操作:
wait
和post
(也称为P
和V
操作),它们可以用来锁定和解锁资源。 wait
操作会将信号量值减少,如果值变为负数,线程就会被阻塞,直到信号量变得非负。post
操作会将信号量值增加,如果有线程在等待信号量,它会唤醒其中一个或多个线程。
-
条件变量(Condition Variable):
- 条件变量是一种同步工具,用于线程之间的通信和等待。
- 条件变量通常与互斥锁(mutex)一起使用,以实现线程的等待和唤醒。
- 条件变量允许线程在某个条件满足之前等待,而不会浪费 CPU 时间。
- 主要操作是
wait
和signal
(或broadcast
),其中:wait
操作将线程置于等待状态,并释放互斥锁,直到其他线程调用signal
来唤醒等待线程。signal
操作用于唤醒一个等待条件的线程。broadcast
操作用于唤醒所有等待条件的线程。
关于它们的关系:
-
条件变量通常与互斥锁一起使用,以确保在等待条件时,访问共享资源是安全的。等待线程在等待之前会释放互斥锁,然后等待条件变量的信号。当条件满足时,其他线程可以通过发出信号来唤醒等待线程。
-
信号量可以用于更通用的同步目的,例如限制同时访问某个资源的线程数量。它不一定与互斥锁和条件变量结合使用,尽管在某些情况下可以一起使用来实现高级同步机制。
总之,信号量和条件变量是不同的同步工具,它们解决了不同类型的多线程编程问题。条件变量通常用于线程之间的通信和等待,而信号量用于资源的控制和限制。在一些情况下,它们可以结合使用,以实现更复杂的同步需求。
sem_t
是 POSIX 线程库中用于表示信号量的数据类型,它用于实现进程间或线程间的同步和互斥。sem_t
信号量不是用于上锁的,而是用于控制资源的访问。
信号量(Semaphore)是一种计数器,它的值可以表示可用的资源数量。在多线程或多进程环境中,通过操作信号量的值,可以实现对共享资源的控制,例如实现互斥锁或条件变量等。
信号量的常见操作包括 sem_wait
(等待信号量减小)、sem_post
(增加信号量)和 sem_init
(初始化信号量)等。这些操作允许多个线程或进程协调访问共享资源,但信号量本身并不提供锁的机制。
// 信号量的类型 sem_t
int sem_init(sem_t *sem, int pshared, unsigned int 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
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 <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
// 创建链表结构体
struct Node
{
int num;
struct Node *next;
};
struct Node *head = NULL;
// 创建互斥量
pthread_mutex_t mutex;
// 创建信号量
sem_t psem;
sem_t csem;
// 生产者
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 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 = (struct Node *)malloc(sizeof(struct Node));
tmp = head;
head = head->next;
printf("del 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(100);
}
// 销毁互斥量
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
return 0;
}
ernest-laptop@ubuntu:~/Linux/lesson30$ gcc semaphore.c -o semaphore -lpthread
ernest-laptop@ubuntu:~/Linux/lesson30$ ./semaphore
...
add num : 679, tid : 140167046223616
add num : 831, tid : 140167046223616
add num : 228, tid : 140167152805632
del num : 228, tid : 140167037830912
del num : 831, tid : 140167037830912
del num : 679, tid : 140167037830912
...