目录
共享资源访问互斥
并发程序,多进程与多线程是会并发访问这些共享数据,为了避免多进程访问共享数据冲突,我们要学会资源访问互斥:锁,保证资源一个时刻内被一个线程访问。
数据库自带锁机制。
互斥锁等待队列:系统向某个线程发送标记,受到标记的线程等待唤醒。
就近原则,如果线程释放资源后立即请求资源,系统会根据就近原则把资源分配给此线程。
你叫早期的互斥锁,当锁被释放,所有等待锁的线程都被唤醒,而后争抢互斥锁。惊群问题,资源有限却将所有等待资源的单位唤醒,只有少数能得到资源,但是却有庞大的控制开销,需要系统承担。
互斥锁
pthread_mutex_t lock;互斥锁类型
pthread_mutex_t=PTHREAD_MUTEX_INITIALIZER//静态初始化
pthread_mutex_init(&lock,pthread_mutexattr_t*);//动态初始化
pthread_mutex_destroy(&lock)释放互斥锁
pthread_mutex_lock(&lock)上锁
pthread_mutex_unlock(&lock)解锁
一般还提供非阻塞版本或定时阻塞版本
上锁建议,需要在使用全局资源位置上锁。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
pthread_mutex_t lock;
int num=0;
void* twk(void* arg)
{
int i;
for(i=1;i<=5000;i++)
{
pthread_mutex_lock(&lock);
printf("tid 0x%x,%d\n",pthread_self(),++num);
pthread_mutex_unlock(&lock);
}
pthread_exit(NULL);
}
int main()
{
pthread_t tid;
pthread_mutex_init(&lock,NULL);
int j;
for(j=0;j<2;j++)
pthread_create(&tid,NULL,twk,NULL);
while(1)
sleep(1);
return 0;
}
读写锁
互斥锁资源的利用率不能最大化,不支持多个线程同时访问资源,哪怕是读访问,读共享,读锁有多把,多个线程可以使用读写锁同时读数据,写独占,写锁只有一把,只允许一个线程利用写锁修改数据。读写互斥,读写操作不允许同时进行。
pthread_rwlock_t lock读写锁类型
pthread_rwlock_init(&lock,NULL);动态初始化
pthread_rwlock_destroy(&lock);销毁锁
pthread_rwlock_rdlock(&lock);请求读锁
pthread_rwlock_wrlock(&lock);请求写锁
pthread_rwlock_unlock(&lock);解锁
动态初始化锁允许用户自定义锁属性,但是静态初始化不支持。请求读锁,如果读锁耗尽,需要阻塞等待锁。
int num=0;
void* read_lock(void* arg)
{
while(1){
pthread_rwlock_rdlock(&rwlock);
printf("tid:0x%x,num:%d read\n",pthread_self(),num);
pthread_rwlock_unlock(&rwlock);
usleep(100000);
}
}
void* write_lock(void* arg)
{
while(1){
pthread_rwlock_wrlock(&rwlock);
printf("tid:0x%x,num:%d\n",pthread_self(),++num);
pthread_rwlock_unlock(&rwlock);
usleep(100000);
}
}
int main()
{
pthread_t tids[8];
int i;
pthread_rwlock_init(&rwlock,NULL);
for(i=0;i<3;i++)
{
pthread_create(&tids[i],NULL,write_lock,NULL);
}
for(i=3;i<8;i++)
{
pthread_create(&tids[i],NULL,read_lock,NULL);
}
while(i--)
pthread_join(tids[i],NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}
进程锁
进程锁也是互斥锁,互斥锁默认情况为线程互斥,在线程间使用,但是我们可以修改互斥锁属性,将线程互斥变为进程互斥,在进程间使用。
1.pthread_mutex_t lock
2.pthread_mutexattr_t attr;互斥锁属性
3.pthread_mutexattr_init();初始化锁属性,默认锁属性(线程互斥)
4.pthread_mutexattr_setpashared(&attr,PTHREAD_PROCESS_SHARED);可以将线程互斥改为进程互斥
5.pthread_mutex_init(&lock,&attr)
6.互斥锁使用完毕,释放互斥锁属性
7.使用完毕释放映射
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/wait.h>
#include<sys/mman.h>
#include<sys/fcntl.h>
typedef struct
{
int code;
pthread_mutex_t lock;
}Message;
int main()
{
pid_t pid;
Message* p;
int fd;
fd=open("processmap",O_CREAT|O_RDWR,0666);
ftruncate(fd,sizeof(Message));
if((p=mmap(NULL,sizeof(Message),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0))==MAP_FAILED)
{
perror("mmap failed\n");
exit(0);
}
p->code=0;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&p->lock,&attr);
pthread_mutexattr_destroy(&attr);
pid=fork();
if(pid>0)
{
pid_t zpid;
int i;
for(i=0;i<5000;i++)
{
pthread_mutex_lock(&p->lock);
printf("parent %d,code %d\n",getpid(),++(p->code));
pthread_mutex_unlock(&p->lock);
}
zpid=wait(NULL);
pthread_mutex_destroy(&p->lock);
munmap(p,sizeof(Message));
}
else if(pid==0)
{
int j;
for(j=0;j<5000;j++)
{
pthread_mutex_lock(&p->lock);
printf("son %d,code %d\n",getpid(),++(p->code));
pthread_mutex_unlock(&p->lock);
}
exit(0);
}
else
{
perror("fork error\n");
exit(0);
}
return 0;
}
自旋锁
旋转锁,当某个线程无法占用锁时,它会持续请求,直到占用为止,它的状态一直是运行态,相比互斥锁的阻塞等待,它的开销较大。因为它不会阻塞等待锁,所以锁的利用率更好一些。
文件锁
如果多线程访问一个文件是可以利用互斥锁这类锁进行保护。多个进程间可以利用文件锁保护数据。
文件属性结构体:
读写指针位置,磁盘存储位置,文件锁属性结构体(对文件上锁需要修改设置文件属性)
文件锁属性结构体:
l_type:表示锁类型:F_UNLCK,F_RDLCK,F_WRLCK
l_whence:上锁的绝对偏移量:SEEK_SET,SEEK_CUR,SEEK_END
l_start:相对偏移量:以绝对偏移量为基准进行进行定位描述,不偏移传0
l_len:上锁长度:如果锁长度大于0按指定长度上锁,如果锁长度等于0,则锁整个文件
l_pid:表示当前占用此文件锁的进程pid
fcntl()//可以修改绝大多数文件属性
fcntl(fd,F_GETLK,struct flock* oldlock);//获取文件默认的锁结构
fcntl(fd,F_SETLK,struct flock* newlock);//设置替换文件锁结构
F_SETLKW阻塞请求锁
#include<stdio.h>
#include<sys/fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd;
fd=open("filelock",O_RDWR);
struct flock newl;
//struct flock oldl;
//fcntl(fd,F_GETLK,&oldl);
//if(oldl->l_type==F_UNLCK)
//{
printf("文件可以加锁\n");
newl.l_type=F_WRLCK;
newl.l_whence=SEEK_SET;
newl.l_start=0;
newl.l_len=0;
fcntl(fd,F_SETLKW,&newl);
printf("文件已上锁\n");
sleep(10);
newl.l_type=F_UNLCK;
fcntl(fd,F_SETLKW,&newl);
printf("文件已解锁\n");
//}
close(fd);
return 0;
}
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/fcntl.h>
int main()
{
int fd;
fd=open("filelock",O_RDWR);
struct flock newl;
newl.l_type=F_WRLCK;
newl.l_whence=SEEK_SET;
newl.l_start=0;
newl.l_len=0;
fcntl(fd,F_SETLKW,&newl);
printf("file lock\n");
sleep(2);
newl.l_type=F_UNLCK;
fcntl(fd,F_SETLKW,&newl);
printf("file unlock\n");
close(fd);
return 0;
}
文件锁使用场景:
可以让并发程序,多进程或多线程共享访问文件,还可以避免冲突,提高文件数据的访问频率。
可以使用互斥锁访问文件,但是相当于独占访问。多线程依然可以使用文件读写锁对文件并发访问。
线程同步与控制调度
条件变量技术
实现线程的控制调度,在多个线程中创建条件(执行条件,挂起条件,多个线程根据条件工作完成挂起或唤醒,实现线程控制)。
pthread_cond_t cd;条件变量类型
pthread_cond_init(&cd,NULL);初始化
pthread_cond_destroy(&cd);销毁
pthread_cond_wait(&cd,&lock);挂起时解锁,被唤醒时再执行一次wait上锁
pthread_cond_signal(&cd);唤醒一个指定条件变量中的线程
pthread_cond_broadcast(&cd);唤醒某个条件变量上的所有线程
绝大多数情况下:条件变量+互斥锁
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
#include<pthread.h>
int day;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cd1=PTHREAD_COND_INITIALIZER;
pthread_cond_t cd2=PTHREAD_COND_INITIALIZER;
void* thread_a(void* arg)
{
while(1)
{
pthread_mutex_lock(&lock);
if(day!=1)
{
pthread_cond_wait(&cd1,&lock);
}
printf("pidA 0x%x,day %d\n",(unsigned int)pthread_self(),day);
day=0;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cd2);
usleep(100000);
}
}
void* thread_b(void* arg)
{
while(1)
{
pthread_mutex_lock(&lock);
if(day!=0)
{
pthread_cond_wait(&cd2,&lock);
}
printf("pidB 0x%x,day %d\n",(unsigned int)pthread_self(),day);
day=1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cd1);
usleep(100000);
}
}
int main()
{
int i=2;
pthread_t tid[2];
pthread_create(&tid[0],NULL,thread_a,NULL);
pthread_create(&tid[1],NULL,thread_b,NULL);
while(i--)
{
pthread_join(tid[i],NULL);
}
return 0;
}
死锁现象
多线程模式下,锁资源使用不当引发的异常(永久挂起)称为死锁问题。
杀死线程可以解决死锁问题,但是不是最优解。
死锁产生的四个必要条件,一个条件不满足死锁不会发生。
1.保持与请求(贪婪)
2.互斥条件(阻塞请求)
3.不可剥夺条件,自己申请的资源只有自己可以释放,其他人不允许干预
4.资源等待环路,总有相邻的线程等待资源
预防死锁方式:
1.用图记录线程以及资源请求路径,可以有效地检测和预防环路的发生。
2.银行家算法,记录银行资产,评估用户借款风险。