线程的同步与互斥
临界资源:
一次只允许一个任务(进程、线程)访问的共享资源
临界区:访问临界资源的代码
互斥机制:mutex互斥锁
任务访问临界资源前申请锁,访问完后释放锁
临界资源概念:
不能同时访问的资源,比如写文件,只能由一个线程写,同时写会写乱。比如外设打印机,打印的时候只能由一个程序使用。外设基本上都是不能共享的资源。生活中比如卫生间,同一时间只能由一个人使用。
必要性: 临界资源不可以共享
man手册找不到 pthread_mutex_xxxxxxx (提示No manual entry for pthread_mutex_xxx)的解决方法:apt-get install manpages-posix-dev
互斥锁的创建和销毁
两种方法创建互斥锁,静态方式和动态方式(#include <pthread.h>)
动态初始化方式:
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
其中mutexattr用于指定互斥锁属性,如果为NULL则使用缺省属性。
> 成功时返回0,失败时返回错误码
> mutex 指向要初始化的互斥锁对象(通过pthread_mutex_t 定义一个互斥锁)
> attr 互斥锁属性,NULL表示缺省属性
静态初始化方式:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
锁的销毁:
int pthread_mutex_destroy(pthread_mutex_t *mutex)
在Linux中,互斥锁并不占用任何资源,因此LinuxThreads中的 pthread_mutex_destroy()除了检查锁状态以外(锁定状态则返回EBUSY)没有其他动作。
互斥锁的使用:
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t *mutex)
int pthread_mutex_trylock(pthread_mutex_t *mutex)
vim 设置代码全文格式化:gg=G
申请锁:
int pthread_mutex_lock(pthread_mutex_ t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex)
> 成功时返回0,失败时返回错误码
> mutex 指向要初始化的互斥锁对象
区别:> pthread_mutex_lock 如果无法获得锁,任务阻塞
> pthread_mutex_trylock 如果无法获得锁,返回EBUSY而不是挂起等待
释放锁:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
> 成功时返回0,失败时返回错误码
> mutex 指向要初始化的互斥锁对象
示例代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
FILE *fp;
void *func2(void *arg){
pthread_detach(pthread_self());
printf("This func2 thread\n");
char str[]="I write func2 line\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);//上锁
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
usleep(1); // usleep(); 微秒
i++;
}
pthread_mutex_unlock(&mutex);//解锁
i=0;
usleep(1);
}
pthread_exit("func2 exit");
}
void *func(void *arg){
pthread_detach(pthread_self());
printf("This is func1 thread\n");
char str[]="You read func1 thread\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);//上锁
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
i++;
usleep(1);
}
pthread_mutex_unlock(&mutex);//解锁
i=0;
usleep(1);
}
pthread_exit("func1 exit");
}
int main(){
pthread_t tid,tid2;
void *retv;
int i;
fp = fopen("1.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
pthread_create(&tid,NULL,func,NULL);
pthread_create(&tid2,NULL,func2,NULL);
while(1){
sleep(1);
}
}
读写锁
必要性:提高线程执行效率
特性:
写者:写者使用写锁,如果当前没有读者,也没有其他写者,写者立即获得写锁;否则写者将等待,直到没有读者和写者。(严格)
读者:读者使用读锁,如果当前没有写者,读者立即获得读锁;否则读者等待,直到没有写者。
注意:
同一时刻只有一个线程可以获得写锁,同一时刻可以有多个线程获得读锁。
读写锁出于写锁状态时,所有试图对读写锁加锁的线程,不管是读者试图加读锁,还是写者试图加写锁,都会被阻塞。
读写锁处于读锁状态时,有写者试图加写锁时,之后的其他线程的读锁请求会被阻塞,以避免写者长时间的不写锁
读者在读的时候,写者处于阻塞态,等待读者读完解锁,写者开始
初始化一个读写锁 pthread_rwlock_init
读锁定读写锁 pthread_rwlock_rdlock
非阻塞读锁定 pthread_rwlock_tryrdlock
写锁定读写锁 pthread_rwlock_wrlock
非阻塞写锁定 pthread_rwlock_trywrlock
解锁读写锁 pthread_rwlock_unlock
释放读写锁 pthread_rwlock_destroy
示例代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_rwlock_t rwlock;
FILE *fp;
void * read_func(void *arg){
pthread_detach(pthread_self());
printf("read thread\n");
char buf[32]={0};
while(1){
//rewind(fp); 重置读指针
pthread_rwlock_rdlock(&rwlock);
while(fgets(buf,32,fp)!=NULL){
printf("%d,rd=%s\n",(int)arg,buf);
usleep(1000);
}
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
void *func2(void *arg){
pthread_detach(pthread_self());
printf("This func2 thread\n");
char str[]="I write func2 line\n";
char c;
int i=0;
while(1){
pthread_rwlock_wrlock(&rwlock);
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
usleep(1);
i++;
}
pthread_rwlock_unlock(&rwlock);
i=0;
usleep(1);
}
pthread_exit("func2 exit");
}
void *func(void *arg){
pthread_detach(pthread_self());
printf("This is func1 thread\n");
char str[]="You read func1 thread\n";
char c;
int i=0;
while(1){
pthread_rwlock_wrlock(&rwlock);
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
i++;
usleep(1);
}
pthread_rwlock_unlock(&rwlock);
i=0;
usleep(1);
}
pthread_exit("func1 exit");
}
int main(){
pthread_t tid1,tid2,tid3,tid4;
void *retv;
int i;
fp = fopen("1.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
pthread_rwlock_init(&rwlock,NULL);
//想让谁先操作可以在它后面加一个sleep
pthread_create(&tid1,NULL,read_func,1);
pthread_create(&tid2,NULL,read_func,2);
pthread_create(&tid3,NULL,func,NULL);
pthread_create(&tid4,NULL,func2,NULL);
while(1){
sleep(1);
}
}
死锁(deadlock)
概念:死锁就是两个或两个以上线程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。
死锁产生的原因:
①互斥条件:一个资源只能被一个线程占有,当这个资源被占用后其他线程就只能等待。
②不可剥夺条件:当一个线程不主动释放资源时,此资源一直被拥有线程占有。
③请求并持有条件:线程已经拥有一个资源后仍然不满足,又尝试请求新的资源。
④环路等待条件:产生死锁一定是发生了线程资源环路链。
示例代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
FILE *fp;
void *func2(void *arg){
pthread_detach(pthread_self());
printf("This func2 thread\n");
char str[]="I write func2 line\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);
printf("%d,I got lock2\n",(int)arg);
sleep(1);//获得第一把锁之后休眠一下
pthread_mutex_lock(&mutex2);
printf("%d,I got 2 locks\n",(int)arg);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
sleep(10);
}
pthread_exit("func2 exit");
}
void *func(void *arg){
pthread_detach(pthread_self());
printf("This is func1 thread\n");
char str[]="You read func1 thread\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);
printf("%d,I got lock1\n",(int)arg);
sleep(1);
pthread_mutex_lock(&mutex2);
printf("%d,I got 2 locks\n",(int)arg);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex);
sleep(10);
}
pthread_exit("func1 exit");
}
int main(){
pthread_t tid,tid2;
void *retv;
int i;
fp = fopen("1.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
pthread_create(&tid,NULL,func,1);
//解决方式:可以在此处加一个sleep,让线程1能够全部获得并归还锁,然后线程2开始运行
pthread_create(&tid2,NULL,func2,2);
while(1){
sleep(1);
}
}
运行结果:线程1获得了锁1,线程2获得了锁2,但是二者都没有得到满足,锁死在此处。
解决之后:
避免方法:
- 锁越少越好,最好使用一把锁
- 调整好锁的顺序(线程1和2都是先争抢锁1再争抢锁2,而不是一个12一个21)
如何解决死锁问题:
改变死锁中的任意一个或多个条件就可以解决死锁问题,其中被修改的条件只有后两个:请求并持有条件和环路等待条件。
修改请求并持有条件:获得了一把锁之后不再去请求获取另一把锁
破坏环路等待条件:如果就是需要两把锁的资源,则可以按照如下流程进行操作:
条件变量
应用场景:生产者消费者问题,是线程同步的一种手段。
必要性 : 为了实现等待某个资源,让线程休眠。提高运行效率
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)//;广播发送信号
使用步骤:
- 1.初始化:
静态初始化(条件变量和互斥量必须同时拥有)
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
或使用动态初始化
pthread_cond_init(&cond);
- 2.生产资源线程:
pthread_mutex_lock(&mutex);
开始产生资源
pthread_cond_signal(&cond); //通知一个消费线程(单播
或者
pthread_cond_broadcast(&cond); //广播通知多个消费线程
pthread_mutex_unlock(&mutex);
消费者线程:
pthread_mutex_lock(&mutex); //先加锁
while (如果没有资源){ //防止惊群效应
pthread_cond_wait(&cond, &mutex);
}
有资源了,消费资源
pthread_mutex_unlock(&mutex); //解锁
示例代码:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
pthread_cond_t hastaxi = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
struct taxi{
int num;
struct taxi *next;
};
struct taxi *H=NULL;
void *taxiarv(void *arg){
printf("taxi arrived\n");
pthread_detach(pthread_self());
struct taxi *tx;
int i=0;
while(1){
tx = malloc(sizeof(struct taxi));
tx->num = i++;
printf("taxi %d comming\n",tx->num);
pthread_mutex_lock(&lock);
tx->next=H;
H = tx; //头结点永远指向链表首部
pthread_cond_signal(&hastaxi); //通知一个消费线程(单播
pthread_mutex_unlock(&lock);
sleep(1); //控制每秒生产一个
}
pthread_exit(0);
}
void *taketaxi(void *arg){
printf("take taxi");
pthread_detach(pthread_self());
struct taxi *tx;
while(1){
pthread_mutex_lock(&lock);//上锁
while(H== NULL){ //循环等待资源
pthread_cond_wait(&hastaxi, &mutex); //cond之前必须要lock
}
tx=H; //取出头
H = tx->next; //头结点指向下一个资源
printf("Take taxi %d \n",tx->num);
free(tx);
pthread_mutex_unlock(&lock);//解锁
}
pthread_exit(0);
}
int main(){
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,taxiarv,NULL);
pthread_create(&tid2,NULL,taketaxi,NULL);
while(1){
sleep(1);
}
}
运行结果:
注意:
1. pthread_cond_wait(&cond, &mutex),在没有资源等待是是先unlock 休眠,等资源到了,再lock
所以pthread_cond_wait he pthread_mutex_lock 必须配对使用。
pthread_mutex_unlock 如果资源没有来 sleep 如果来了 pthread_mutex_lock
2 如果pthread_cond_signal或者pthread_cond_broadcast 早于 pthread_cond_wait ,则有可能会丢失信号。
3 pthead_cond_broadcast 信号会被多个线程收到,这叫线程的惊群效应。所以需要加上判断条件while循环。
线程池概念和使用
概念:
通俗的讲就是一个线程的池子,可以循环的完成任务的一组线程集合
必要性:
我们平时创建一个线程,完成某一个任务,等待线程的退出。但当需要创建大量的线程时,假设T1为创建线程时间,T2为在线程任务执行时间,T3为线程销毁时间,当 T1+T3 > T2,这时候就不划算了,使用线程池可以降低频繁创建和销毁线程所带来的开销,任务处理时间比较短的时候这个好处非常显著。(例如招临时工和招长期工)
线程池的基本结构:
1 任务队列,存储需要处理的任务,由工作线程来处理这些任务
2 线程池工作线程,它是任务队列任务的消费者,等待新任务的信号
线程池的实现:
1.创建线程池的基本结构:
typedef struct Task;// 任务队列链表
typedef struct ThreadPool; // 线程池结构体
2.线程池的初始化:
pool_init()
{
创建一个线程池结构
实现任务队列互斥锁和条件变量的初始化
创建n个工作线程
}
3.线程池添加任务
pool_add_task
{
判断是否有空闲的工作线程
给任务队列添加一个节点
给工作线程发送信号newtask
}
4.实现工作线程
workThread
{
while(1){
等待newtask任务信号
从任务队列中删除节点
执行任务
}
}
5.线程池的销毁
pool_destory
{
删除任务队列链表所有节点,释放空间
删除所有的互斥锁条件变量
删除线程池,释放空间
}
示例代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define POOL_NUM 10
typedef struct Task{ // 定义任务队列链表
void *(*func)(void *arg);
void *arg;
struct Task *next;
}Task;
typedef struct ThreadPool{ // 定义线程池
pthread_mutex_t taskLock; // 定义互斥量
pthread_cond_t newTask; // 通知
pthread_t tid[POOL_NUM]; // 线程数组形式记录tid
Task *queue_head; // 任务队列队头
int busywork;
}ThreadPool;
ThreadPool *pool; // 定义线程池全局变量
// 工作线程
void *workThread(void *arg){
while(1){
pthread_mutex_lock(&pool->taskLock);// 访问工作队列(加锁
pthread_cond_wait(&pool->newTask,&pool->taskLock);// 等待任务队列
Task *ptask = pool->queue_head; // 从队头取出任务
pool->queue_head = pool->queue_head->next; // 修改任务队列头指针位置
pthread_mutex_unlock(&pool->taskLock);// 访问工作队列结束(解锁
ptask->func(ptask->arg); // 真正的执行!!!
pool->busywork--; // 工作线程数-1;
}
}
void *realwork(void *arg){
printf("Finish work %d\n",(int)arg);
}
/*
判断是否有空闲的工作线程
给任务队列添加一个节点
给工作线程发送信号newtask
*/
void pool_add_task(int arg){
Task *newTask; //定义新的任务
// 访问临界资源taskLock之前要加锁
pthread_mutex_lock(&pool->taskLock);
while(pool->busywork>=POOL_NUM){//判断是否有空闲的工作线程
pthread_mutex_unlock(&pool->taskLock);// 休眠时要释放锁
usleep(10000);
pthread_mutex_lock(&pool->taskLock);
}
pthread_mutex_unlock(&pool->taskLock);
newTask = malloc(sizeof(Task)); // 分配新的任务
// 执行真正的工作(通过 函数指针 赋值)
//真正的执行在workThread()当中
newTask->func = realwork;
newTask->arg = arg;
pthread_mutex_lock(&pool->taskLock);
Task *member = pool->queue_head; //
if(member==NULL){ //空任务
pool->queue_head = newTask; //直接把任务挂在队列头
}else{
//遍历寻找队列队尾
while(member->next!=NULL){
member=member->next;
}
member->next = newTask; //把newtask 新任务加入队尾
}
pool->busywork++; //多了一个任务
pthread_cond_signal(&pool->newTask); //发信号告知有新任务
pthread_mutex_unlock(&pool->taskLock);
}
// 初始化
void pool_init(){
int i;
pool = malloc(sizeof(ThreadPool));
pthread_mutex_init(&pool->taskLock,NULL);
pthread_cond_init(&pool->newTask,NULL);
pool->queue_head = NULL;
pool->busywork=0;
// 创建工作线程
for(i=0;i<POOL_NUM;i++){
pthread_create(&pool->tid[i],NULL,workThread,NULL);
}
}
//销毁线程池
void pool_destory(){
Task *head;
//循环删除队列数据
while(pool->queue_head!=NULL){
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free(head);
}
//销毁互斥量、条件变量、释放线程池
pthread_mutex_destroy(&pool->taskLock);
pthread_cond_destroy(&pool->newTask);
free(pool);
}
int main(){
pool_init(); //初始化
int i;
sleep(20);
//循环创建任务
for(i=1;i<=20;i++){
pool_add_task(i);
}
sleep(5);
pool_destory(); //销毁线程池
}
线程的GDB调试
- 显示线程: info thread
-
切换线程: thread id (如 thread 3)
-
GDB为特定线程设置断点: break location thread id (如b 6 thread 3)
-
GDB设置线程锁:set scheduler-locking on/off
on:其他线程会暂停。可以单独调试一个线程