8.线程的同步和互斥
概念
-
临界资源: 一次只允许一个任务(进程、线程)访问的共享资源
-
临界区:访问临界资源的程序
-
互斥机制:mutex互斥锁,任务访问临界资源前申请锁,访问完后释放锁
互斥锁
互斥锁创建
-
动态方式:
-
int pthread_mutex_init(pthread_mutex_t *restrict **mutex**,const pthread_mutexattr_t *restrict attr);
-
mutexattr:指定互斥锁属性,如果为NULL则使用缺省属性。
-
-
静态方式:
pthread_mutex_t **mutex** = PTHREAD_MUTEX_INITIALIZER;
- mutex:锁的名称
锁的销毁
-
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);
pthread_mutex_lock
如果无法获得锁,任务阻塞
int pthread_mutex_trylock(pthread_mutex_t *mutex);
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 mutex1 = PTHREAD_MUTEX_INITIALIZER;//互斥锁创建锁
FILE *fp;
void *fun1(void *arg)
{
int i;
char c = 'A';
pthread_detach(pthread_self());//分离线程
printf("fun1...\n");
i=0;
pthread_mutex_lock(&mutex1);//互斥锁上锁
while(i<26)
{
printf("%d\n",i);
fputc(c+i,fp);
usleep(1);
i++;
}
fputc('\n',fp);
fflush(fp);//刷新流
pthread_mutex_unlock(&mutex1);//互斥锁解锁
pthread_exit("fun1 exit");
}
void *fun2(void *arg)
{
int i;
char c = 'a';
pthread_detach(pthread_self());//分离线程
printf("fun2...\n");
i=0;
pthread_mutex_lock(&mutex1);//互斥锁上锁
while(i<26)
{
printf("%d\n",i);
fputc(c+i,fp);
usleep(1);
i++;
}
fputc('\n',fp);
fflush(fp);//刷新流
pthread_mutex_unlock(&mutex1);//互斥锁解锁
pthread_exit("fun2 exit");
}
int main()
{
pthread_t tid1,tid2;
void *retv;
int i;
fp = fopen("1.txt","a+");//读写方式打开文件
if(fp==NULL)
{
perror("fopen");
return 0;
}
pthread_create(&tid1,NULL,fun1,NULL);
pthread_create(&tid2,NULL,fun2,NULL);
sleep(5);
return 0;
}
man手册找不到
pthread_mutex_xxxxxxx (提示No manual entry for pthread_mutex_xxx)的解决方法:
输入命令:sudo apt-get install manpages-posix-dev
读写锁
提高线程执行效率
特性
写者:写者使用写锁,如果当前没有读者,也没有其他写者,写者立即获得写锁;否则写者将等待,直到没有读者和写者。
读者:读者使用读锁,如果当前没有写者,读者立即获得读锁;否则读者等待,直到没有写者。
注意
同一时刻只有一个线程可以获得写锁,同一时刻可以有多个线程获得读锁。
读写锁出于写锁状态时,所有试图对读写锁加锁的线程,不管是读者试图加读锁,还是写者试图加写锁,都会被阻塞。
读写锁处于读锁状态时,有写者试图加写锁时,之后的其他线程的读锁请求会被阻塞,以避免写者长时间的不写锁
相关函数
#include <pthread.h>
- pthread_rwlock_init 初始化一个读写锁
- int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
- pthread_rwlock_rdlock 读锁定读写锁
- int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
- pthread_rwlock_tryrdlock 非阻塞读锁定
- int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
- pthread_rwlock_wrlock 写锁定读写锁
- int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
- pthread_rwlock_trywrlock 非阻塞写锁定
- int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
- pthread_rwlock_unlock 解锁读写锁
- int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
- pthread_rwlock_destroy 释放读写锁
- int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
示例
创建两个读进程两个写进程,利用读写锁让它们互不干扰
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <string.h> pthread_rwlock_t rwlock;//创建读写锁 FILE *fp; void *fun1(void *arg) { int i; char c = 'A'; pthread_detach(pthread_self());//分离线程 printf("fun1...\n"); i=0; pthread_rwlock_wrlock(&rwlock);//写锁上锁 while(i<26) { fputc(c+i,fp); usleep(1); i++; } fputc('\n',fp); fflush(fp);//刷新流 pthread_rwlock_unlock(&rwlock);//解锁 pthread_exit("fun1 exit"); } void *fun2(void *arg) { int i; char c = 'a'; pthread_detach(pthread_self());//分离线程 printf("fun2...\n"); i=0; pthread_rwlock_wrlock(&rwlock);//写锁上锁 while(i<26) { fputc(c+i,fp); usleep(1); i++; } fputc('\n',fp); fflush(fp);//刷新流 pthread_rwlock_unlock(&rwlock);//解锁 pthread_exit("fun2 exit"); } void * fun3_read(void *arg)//读进程 { pthread_detach(pthread_self());//分离线程 printf("fun3_read...\n"); char buf[32]={0}; while(1) { 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); } pthread_exit("fun3 exit"); } void * fun4_read(void *arg)//读进程 { pthread_detach(pthread_self());//分离线程 printf("fun4_read...\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); } pthread_exit("fun4 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);//初始化读写锁 pthread_create(&tid1,NULL,fun1,NULL); pthread_create(&tid2,NULL,fun2,NULL); pthread_create(&tid3,NULL,fun3_read,(void *)3); pthread_create(&tid4,NULL,fun4_read,(void *)4); sleep(5); return 0; }
死锁
死锁是指两个或多个进程在执行过程中,因争夺资源而造成的一种相互等待的永久阻塞状态。
死锁通常发生在多任务环境中,当两个或多个进程各自持有一部分资源,同时又互相等待对方释放另一部分资源时,就会产生死锁。这种现象在操作系统、数据库系统以及并发程序中都有可能出现。
产生死锁需要满足以下四个必要条件:
- 互斥条件:资源至少有一个是不能被共享的,即一次只能由一个进程使用。
- 占有和等待条件:一个进程至少已经持有一个资源,且正在请求额外的资源,而该资源可能被其他进程持有。
- 非抢占条件:已经分配给进程的资源在未使用完之前不能被其他进程强行夺走,只能被占有它的进程释放。
- 循环等待条件:存在一种进程资源的循环等待链,每个进程持有下一个进程所需的至少一个资源。
解决和避免死锁的方法包括:
- 按照顺序加锁:对资源进行编号,并规定所有进程按照固定的顺序请求资源,以避免循环等待。
- 设置获取锁的超时时间:限制进程等待资源的时间,若在指定时间内无法获取所需资源,则放弃已占有的资源或者回退操作。
- 死锁检测与恢复:通过系统工具定期检测系统的资源分配情况,一旦发现死锁,采取措施解除死锁,如中断其中一个进程或者回收资源等